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.
Try:
Four changes:
&&
to||
{ }
in place of( )
;
afterexit
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&&
.will run
cmd2
whencmd1
succeeds(exit value0
). Where aswill run
cmd2
whencmd1
fails(exit value non-zero).Using
( )
makes the command inside them run in a sub-shell and calling aexit
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.
Provided
my_command
is canonically designed, ie returns 0 when succeeds, then&&
is exactly the opposite of what you want. You want||
.Also note that
(
does not seem right to me in bash, but I cannot try from where I am. Tell me.The
trap
shell builtin allows catching signals, and other useful conditions, including failed command execution (i.e., a non-zero return status). So if you don't want to explicitly test return status of every single command you can saytrap "your shell code" ERR
and the shell code will be executed any time a command returns a non-zero status. For example:trap "echo script failed; exit 1" ERR
Note that as with other cases of catching failed commands, pipelines need special treatment; the above won't catch
false | true
.