i am writing a shell script which should exit in some cases, my current code is:
set -e
Running A || (echo "failed to run A"; exit 1)
Running B || (echo "failed to run B"; exit 1)
if Condition C
then
Running D || (echo "failed to run D"; exit 1)
....
and it worked as expected, it passes if A/B runs well, echo message for me if A or B failed, but i have not tested D failed yet. My understanding is if A or B failed, it will go to code after "||", echo error, then exit subshell and return false. So the whole line is "false||false" so it exited because i have "set -e" at the beginning. But then i read How to exit if a command failed? it mentioned "set -e" is dangerous because it won't be triggered inside if statement, so does it mean that it won't work if my "Running D" command fails?(meanning it won't exit and will continue executing next command). Also, i tried to use {} as the above post suggests, but it's weird. if i change it to:
#set -e
Running A || {exit 1}
it's correct, meaning if A successes, continue next command, if A fails, exit script. But if i change to
#set -e
Running A || {echo "running A failed";exit 1}
it always exited here no matter A successes or fails.
What is wrong? Also i am a bit confused now which is the best way to exit in my case? i should use "set -e" or "{}"? Thanks!