Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Bash script, how can I exit the entire script if a certain condition occurs?

I'm writing a script in Bash to test some code. However, it seems silly to run the tests if compiling the code fails in the first place, in which case I'll just abort the tests.

Is there a way I can do this without wrapping the entire script inside of a while loop and using breaks? Something like a dun dun dun goto?

like image 442
samoz Avatar asked Sep 04 '09 09:09

samoz


People also ask

How do you terminate a shell script if statement?

To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.

How do you exit a shell script if one part of it 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 shell script in Unix?

exit-Issuing the exit command at the shell prompt will cause the shell to exit. In some cases, if you have jobs running in the background, the shell will remind you that they are running and simply return you to the command prompt. In this case, issuing exit again will terminate those jobs and exit the shell.


2 Answers

Use set -e

#!/bin/bash  set -e  /bin/command-that-fails /bin/command-that-fails2 

The script will terminate after the first line that fails (returns nonzero exit code). In this case, command-that-fails2 will not run.

If you were to check the return status of every single command, your script would look like this:

#!/bin/bash  # I'm assuming you're using make  cd /project-dir make if [[ $? -ne 0 ]] ; then     exit 1 fi  cd /project-dir2 make if [[ $? -ne 0 ]] ; then     exit 1 fi 

With set -e it would look like:

#!/bin/bash  set -e  cd /project-dir make  cd /project-dir2 make 

Any command that fails will cause the entire script to fail and return an exit status you can check with $?. If your script is very long or you're building a lot of stuff it's going to get pretty ugly if you add return status checks everywhere.

like image 23
Shizzmo Avatar answered Oct 21 '22 15:10

Shizzmo


Try this statement:

exit 1 

Replace 1 with appropriate error codes. See also Exit Codes With Special Meanings.

like image 94
Michael Foukarakis Avatar answered Oct 21 '22 14:10

Michael Foukarakis