'While loop in shell script not working in the linux bash shell
Am kind of newbie in writing shell scripts in linux. Its a csh script but am running it in the bash shell that why I used #!/bin/bash instead of #!/bin/csh.
1 #!/bin/bash
2 set i = 1
3 echo it starts
4
5 while ($i <= 5)
6 echo i is $i
7 @ i= $i +1
8 end
**Note: ** The numbers are just to number the lines.
The above code gives me the output with error:
it starts ./me.csh: line 9: syntax error: unexpected end of file
I can't figure out what is wrong even though it echos it starts and there is no line number 9 as specified in the error.
Solution 1:[1]
Try this:
#!/bin/bash
echo it starts
i=1
while [ $i -le 5 ]; do
echo i is $i
i=$(( i+1 ))
done
Sample output:
it starts
i is 1
i is 2
i is 3
i is 4
i is 5
Here is a great reference:
Solution 2:[2]
you should use Visual Studio Code with some extensions to check bash script syntax. I use Vscode in Window 10 WSL2 to run bash script.
change (...) to ((...)) to fix error syntax:
#!/bin/bash
a=5
while ((a > 0)); do
echo "a = $a"
a=$((a - 1))
done
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | HungNM2 |
