« JavaScript: edit web page in browser | Home | Oracle: check the existance of logon/logoff triggers »

Unix shell: workaround for loop problem

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

Example:

#!/bin/ksh

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

echo "Number=$num"

This script will return "Number=0" as the result.

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

#!/bin/ksh

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

echo "Number=$l"

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

Topics: Unix Shell | Submitter: checkthis

One Response to “Unix shell: workaround for loop problem”

  1. Bookmarks about Shell Says:
    August 2nd, 2008 at 4:07 pm

    [...] - bookmarked by 4 members originally found by spiralgirl on July 16, 2008 Unix shell: workaround for loop problem http://code.techinterviews.com/shell-workaround-for-loop-problem/120 - bookmarked by 2 members [...]

Comments

You must be logged in to post a comment.

Keep on coding