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.
Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.
One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.
To silence the output of a command, we redirect either stdout or stderr — or both — to /dev/null. To select which stream to redirect, we need to provide the FD number to the redirection operator.
Try:
my_command || { echo 'my_command failed' ; exit 1; }
Four changes:
&&
to ||
{ }
in place of ( )
;
after exit
and{
and before }
Since you want to print the message and exit only when the command fails ( exits with non-zero value) you need a ||
not an &&
.
cmd1 && cmd2
will run cmd2
when cmd1
succeeds(exit value 0
). Where as
cmd1 || cmd2
will run cmd2
when cmd1
fails(exit value non-zero).
Using ( )
makes the command inside them run in a sub-shell and calling a exit
from there causes you to exit the sub-shell and not your original shell, hence execution continues in your original shell.
To overcome this use { }
The last two changes are required by bash.
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 like if
tests) will cause the script to abort. For certain scripts, it's very useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With