LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Bash script - if error then [do something] (https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-if-error-then-%5Bdo-something%5D-905090/)

Orange Sunshine 09-26-2011 11:49 AM

Bash script - if error then [do something]
 
Hello,

So I have a bash script with the set -e flag and for the most part it does exactly what I need it to. If there is an error executing something within the script it will break out of the script as to not cascade error on top of error.

My issue is, I have some cleanup that is done at the end of the script and this cleanup needs to happen before running the script again (the script will error out if cleanup isn't done). If there is an error while executing I have to go and perform that cleanup manually before I can try to run it again. Is there any way to basically say - if there is an error then perform this cleanup first then break out of the script?

colucix 09-26-2011 12:06 PM

You can try a trap. You can make the script catch every error signal coming from the commands inside the script and cause it to execute everything you want before exiting. Example:
Code:

#!/bin/bash
trap "echo ERR signal received" ERR

The command inside double quotes will be executed every time the shell catches an error, but you can also execute it upon EXIT, so that you can execute the same command independently from the fact it fails or terminates successfully:
Code:

#!/bin/bash
trap "do something here and now" ERR EXIT

A brief explanation here: http://tldp.org/LDP/Bash-Beginners-G...ect_12_02.html

Orange Sunshine 09-26-2011 01:16 PM

Quote:

Originally Posted by colucix (Post 4482714)
You can try a trap. You can make the script catch every error signal coming from the commands inside the script and cause it to execute everything you want before exiting. Example:
Code:

#!/bin/bash
trap "echo ERR signal received" ERR

The command inside double quotes will be executed every time the shell catches an error, but you can also execute it upon EXIT, so that you can execute the same command independently from the fact it fails or terminates successfully:
Code:

#!/bin/bash
trap "do something here and now" ERR EXIT

A brief explanation here: http://tldp.org/LDP/Bash-Beginners-G...ect_12_02.html

Looks like exactly what I need, thanks! I'll try it out.

Orange Sunshine 09-26-2011 01:53 PM

Works great, thanks again!

colucix 09-26-2011 02:03 PM

You're welcome!


All times are GMT -5. The time now is 05:42 PM.