I am a noob in shell-scripting. I want to print a message and exit my script if a command fails. I've tried:
my_command && (echo 'my_command failed; exit)
but it does not work. It keeps executing the instructions following this line in the script. I'm using Ubuntu and bash.
For error proofing your commands:
Inspired in Lean manufacturing:
The other answers have covered the direct question well, but you may also be interested in using
set -e
. With that, any command that fails (outside of specific contexts likeif
tests) will cause the script to abort. For certain scripts, it's very useful.You can also use, if you want to preserve exit error status, and have a readable file with one command per line:
This, however will not print any additional error message. But in some cases, the error will be printed by the failed command anyway.
If you want that behavior for all commands in your script, just add
at the beginning of the script. This pair of options tell the bash interpreter to exit whenever a command returns with a non-zero exit code.
This does not allow you to print an exit message, though.
I've hacked up the following idiom:
Precede each command with an informative echo, and follow each command with that same
if [ $? -ne 0 ];...
line. (Of course, you can edit that error message if you want to.)Note also, each command's exit status is stored in the shell variable $?, which you can check immediately after running the command. A non-zero status indicates failure: