Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading