11

When I’m using for like

 for i in 1 2 3 4 5 

then my file contains #!/bin/sh at the top.

But when I’m using

for(( i = 0; i<=5; i++))

then it is showing error

Syntax error: Bad for loop variable

and running properly when I remove shebang. Please tell me the reason behind this.

4 Answers 4

12

for(( i = 0; i<=5; i++)) is Bash specific and doesn't work with plain Bourne shell (/bin/sh).

If you remove the shebang the script is run by your current shell (which likely is Bash) so it works.

Replace #!/bin/sh with #!/bin/bash to make the shebang work.

3
  • Is there any way to do it in sh mode? Thanks! Feb 26, 2014 at 18:48
  • 2
    i=0; while [ $i -le 5 ]; do echo $i; i=$((i+1)); done Feb 26, 2014 at 19:32
  • 1
    I use #bash already and not works
    – Bruno
    Jun 23, 2018 at 1:33
2

I have solved this problem by using ./ instead of sh command. For an example if you put sh test.sh instead just make your command as ./test.sh And most probably problem will be solved.

2
for(( i = 0; i<=5; i++))

for this type of loop only runs on Bash shell. so, if you want to run this, then try this command :

$bash filename.sh

I think It will work fine. and see this one also.

0

Try this out may be this could solve your problem

#!/bin/bash
j=0
for (( i=1; i <= 5; i++ ))
do
 echo "the loop is runing $i time: and value of j is $j"
 j=`expr $j + 1`
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .