Running a function when an error occurs in a bash script

How can I call a function when a command in bash returns an exit code from 1? I know that set -e at the top will just end my code, but I want to call this function first. If the code works fine, I want it to exit normally without the function being called. I do not want to do a check $? after each line. I'm sure there is an easy way to do this, but I'm new to bash scripts, so I don't know it hand to hand.

+4
source share
1 answer

Set the trap to the ERR pseudo ERR :

 set -e error_handler () { # do stuff here } trap error_handler ERR 
+3
source

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


All Articles