web analytics

Unix shell: workaround for loop problem

It’s not possible to get the value of the loop variables in some versions of ksh.



cat $0 | while read line ; do
 let num=num+1

echo "Number=$num"

This script will return “Number=0” as the result on some Linux machines.

Here is the workaround for the problem: You should change the redirection method for the input file.


while read line ; do
 let l=l+1
done < $0

echo "Number=$l"

The last script will return the correct result: “Number=9”

Another possibility is to use the named pipe:


mkfifo $TMPPIPE
cat $0 > $TMPPIPE &
while read line ; do
 let num=num+1
done < $TMPPIPE

echo "Number=$num"

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>




This site uses Akismet to reduce spam. Learn how your comment data is processed.


A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna, tincidunt vitae molestie nec, molestie at mi. Nulla nulla lorem, suscipit in posuere in, interdum non magna.