Bash: how to set -e trap but not exit

My scripts have the first instruction:

set -e 

Thus, whenever an error occurs, the script is aborted. I would like to lure this situation to show an informational message, but I do not want to show this message when the script exits; ONLY when set -e causes abortions. Is it possible to catch this situation?

It:

 set -e function mytrap { echo "Abnormal termination!" } trap mytrap EXIT error echo "Normal termination" 

Called in any output (whether an error occurs or not), which I do not want.

+5
source share
1 answer

Instead of using trap on EXIT use it in the ERR event:

 trap mytrap ERR 

Full code:

 set -e function mytrap { echo "Abnormal termination!" } trap mytrap ERR (($#)) && error echo "Normal termination" 

Now run it to generate errors:

 bash sete.sh 123 sete.sh: line 9: error: command not found Abnormal termination! 

And here is the normal output:

 bash sete.sh Normal termination 
+5
source

Source: https://habr.com/ru/post/1262702/


All Articles