Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit if a command failed? [duplicate]

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.

like image 800
user459246 Avatar asked Sep 29 '10 14:09

user459246


People also ask

How do you exit a script if command fails?

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.

How do you exit a bash script?

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”.

How do I turn off output in bash?

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.


2 Answers

Try:

my_command || { echo 'my_command failed' ; exit 1; } 

Four changes:

  • Change && to ||
  • Use { } in place of ( )
  • Introduce ; after exit and
  • spaces after { 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.

like image 174
codaddict Avatar answered Oct 05 '22 19:10

codaddict


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.

like image 20
Daenyth Avatar answered Oct 05 '22 19:10

Daenyth