3

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

1
  • 1
    If you are doing a loop over particular values of i, you don't want a while loop. You want: for((i=0;i<2;i++)); do ... ; done Commented Dec 20, 2017 at 15:13

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.