While loop in shell script not working in the linux bash shell - TagMerge
4While loop in shell script not working in the linux bash shellWhile loop in shell script not working in the linux bash shell

While loop in shell script not working in the linux bash shell

Asked 1 years ago
2
4 answers

The shebang must be set to the shell that should interpret the script. It doesn't matter which shell you run the script from. The only thing that matters is the language the script is written in.

Your script is written in csh, and must therefore have the shebang #!/bin/csh. This is true even if you want to run it from bash. Also, you were missing a space in your at-sign-ment:

$ cat me.csh
#!/bin/csh
set i = 1
echo it starts

while ($i <= 5)
        echo i is $i
        @ i = $i + 1
end

Output:

$ ./me.csh
it starts
i is 1
i is 2
i is 3
i is 4
i is 5

Source: link

0

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:

BASH Programming - Introduction HOW-TO

Source: link

0

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

Source: link

0

while [condition - should evaluate to TRUE or FALSE]
do
    command 
    command
done
i=0
while [ $i -le 10 ]
do
    echo True
    ((i++))
done
echo False
Now that we figured how to add a condition to terminate the while loop, let’s see how we can work on an infinite while loop. The only thing we’ll have to do is to skip the condition part.
i=0
while :
do
    echo Script ran $i times
    ((i++))
done
echo False

Source: link

Recent Questions on linux

    Programming Languages