rashok
rashok

Reputation: 13474

Syntax for a Bash single-line while loop with condition

I gone through single line inifinite while loop in bash, and trying to add a single line while loop with condition. Below I have mentioned my command, which gives unexpected result (It is suppose to stop after 2 iterations, but it never stops. And also it considers variable I as executable).

Command:

i=0; while [ $i -lt 2 ]; do echo "hi"; sleep 1; i = $i + 1; done

Output:

hi
The program 'i' is currently not installed. To run 'i' please ....
hi 
The program 'i' is currently not installed. To run 'i' please ....
hi 
The program 'i' is currently not installed. To run 'i' please ....
...
...

Note: I am running it on Ubuntu 14.04

Upvotes: 3

Views: 12646

Answers (2)

Inian
Inian

Reputation: 85855

bash is particular about spaces in variable assignments. The shell has interpreted i = $i + 1 as a command i and the rest of them as arguments to i, that is why you see the errors is saying i is not installed.

In bash just use the arithmetic operator (See Arithmetic Expression),

i=0; while [ "$i" -lt 2 ]; do echo "hi"; sleep 1; ((i++)); done

You could use the arithmetic expression in the loop context also

while((i++ < 2)); do echo hi; sleep 1; done

POSIX-ly

i=0; while [ "$i" -lt 2 ]; do echo "hi"; sleep 1; i=$((i+1)); done

POSIX shell supports $(( )) to be used in a math context, meaning a context where the syntax and semantics of C's integer arithmetic are used.

Upvotes: 9

sahaquiel
sahaquiel

Reputation: 1838

i=0; while [ $i -lt 2 ]; do echo "hi"; sleep 1; i=$(($i + 1)); done

Upvotes: 2

Related Questions