shelltcsh

Shell script while loop inside a for loop


with tcsh, I want to print "Hello" for each x,y, z, e, and f. But with the following script, it only prints x. Can someone tell me how to print "Hello" also for y, z, e, and f?

#! /bin/tcsh -f
set arr=(x y z e f)

set j = 0
foreach i ($arr)
echo $i
   while ($j < 5)

     echo "Hello"
     @ j++
    end
end 

The result is:
x
Hello
Hello
Hello
Hello
Hello
y
z
e
f


Solution

  • Move the initialization of the 'j' variable inside the foreach loop:

    #! /bin/tcsh -f
    set arr=(x y z e f)
    
    foreach i ($arr)
        echo $i
        set j = 0
        while ($j < 5)
                echo "Hello"
                @ j++
        end
    end 
    

    Output:

    $ ./s.sh
    x
    Hello
    Hello
    Hello
    Hello
    Hello
    y
    Hello
    Hello
    Hello
    Hello
    Hello
    z
    Hello
    Hello
    Hello
    Hello
    Hello
    e
    Hello
    Hello
    Hello
    Hello
    Hello
    f
    Hello
    Hello
    Hello
    Hello
    Hello