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( );afterexitand{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
cmd2whencmd1succeeds(exit value0). Where aswill run
cmd2whencmd1fails(exit value non-zero).Using
( )makes the command inside them run in a sub-shell and calling aexitfrom 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.