The following code will cause the 'if' statement to exit early and not execute the 'echo' command in the 'if' block. I am wondering why this happens only in the 'if' block but not in the main part of the script. Note: I understand changing ':=' to ':-' will solve the problem - I am not looking to fix the problem, I am looking to understand the difference between the execution environment of the 'if' block that causes it to happen in the first place.
#!/bin/bash
if true; then
VAR=${$1:='val'}
echo "This does not run"
fi
VAR=${$1:='val'}
echo "This does run"
The output is
line 4: ${$1:='val'}: bad substitution
line 7: ${$1:='val'}: bad substitution
This does run
Again - I am not interested in fixing the bad substitution error message, I understand how to do that and why it happens. What I want to understand is why the echo "This does not run"
line does not run when there is a bad substitution above it in an 'if' block.
Reproduced on the following bash versions:
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
GNU bash, version 5.1.16(1)-release (x86_64-pc-msys)
andGNU bash, version 5.0.3(1)-release (arm-unknown-linux-gnueabihf)
if true; then ( VAR=${$1:='val'} ); echo "This does not run"; fi
. That makes it run theecho
.