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 variableand running properly when I remove shebang. Please tell me the reason behind this.
4 Answers
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.
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.shI think It will work fine. and see this one also.
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.
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