Seeni Jabez
Seeni Jabez

Reputation: 33

Bash-like for loop in the Bourne and Korn shells?

I need to read an input from the user (N) and execute the loop N times to perform a set of statements. In bash, I can use the following for-loop syntax:

read N 
for((i=0;i<$N;i++)) 
set of statements 

However, I can't use that syntax in shells such as sh or ksh. What should I do, instead?

Upvotes: 2

Views: 91

Answers (1)

jub0bs
jub0bs

Reputation: 66354

If your script must be compatible with the Bourne shell (sh), be aware that the latter doesn't offer the numeric, "C-like" for-loop syntax (for((i=0;i<$N;i++))). However, you can use a while loop, instead.

Here is a POSIX-compliant approach, which works as expected with both sh and ksh:

read N

i=0                   # initialize counter
while [ $i -lt $N ]
do
  printf %s\\n "foo"  # statements ... 
  i=$((i+1))         # increment counter
done

Tests:

$ sh test.sh 
3
foo
foo
foo
$ ksh test.sh 
4
foo
foo
foo
foo
$ dash test.sh  # (dash is a minimalist, POSIX-compliant shell)
2
foo
foo

Upvotes: 3

Related Questions