Consider these three bash scripts:
- script without a syntax error - executes without errors, as expected, loops "this is the end: -1":
#!/bin/bash
while true ; do
x=1 # or, read the variable from some external source
y=2 # or, read the variable from some external source
z=$(( $x - $y ))
echo "this is the result: $z"
sleep 1
done
Execution - infinite loop, until we interrupt:
$ bash test.sh
this is the result: -1
this is the result: -1
this is the result: -1
^C
- script which results in a syntax error (note the missing x and y variables, which are then needed for a calculation):
#!/bin/bash
while true ; do
x= # or, read the variable from some external source
y= # or, read the variable from some external source
z=$(( $x - $y ))
echo "this is the result: $z"
sleep 1
done
Execution - bash interrupts script execution when there is a syntax error:
$ bash test.sh
test.sh: line 6: - : syntax error: operand expected (error token is "- ")
- script without a while loop - script execution is not interrupted:
#!/bin/bash
x=
y=
z=$(( $x - $y ))
echo "this is the result: $z"
Execution - bash notices a syntax error in calculation, but does NOT interrupt script execution:
$ bash test.sh
test.sh: line 5: - : syntax error: operand expected (error token is "- ")
this is the result:
Why does bash behave differently upon getting a syntax error, depending on whether it's in a while loop or not? EDIT: I'm aware input variables could/should be verified, and there are various ways to do it. I was more interested why it behaves differently, depending on whether we're in a while loop or not.