<p>What is your favorite method to handle errors in Bash? 
The best example of handling errors I have found on the web was written by William Shotts, Jr at <a href="http://www.linuxcommand.org" rel="noreferrer">http://www.linuxcommand.org</a>. </p>

<p>He suggests using the following function for error handling in Bash:</p>

<pre><code>#!/bin/bash

# A slicker error handling routine

# I put a variable in my scripts named PROGNAME which
# holds the name of the program being run.  You can get this
# value from the first item on the command line ($0).

# Reference: This was copied from &lt;http://www.linuxcommand.org/wss0150.php&gt;

PROGNAME=$(basename $0)

function error_exit
{

#   ----------------------------------------------------------------
#   Function for exit due to fatal program error
#       Accepts 1 argument:
#           string containing descriptive error message
#   ---------------------------------------------------------------- 

    echo "${PROGNAME}: ${1:-"Unknown Error"}" 1&gt;&amp;2
    exit 1
}

# Example call of the error_exit function.  Note the inclusion
# of the LINENO environment variable.  It contains the current
# line number.

echo "Example of error with line number and message"
error_exit "$LINENO: An error has occurred."
</code></pre>

<p>Do you have a better error handling routine that you use in Bash scripts?</p>

[{'answer_id': 64880, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 2, 'selected': False, 'text': "<p>I've used</p>\n\n<pre><code>die() {\n        echo $1\n        kill $$\n}\n</code></pre>\n\n<p>before; i think because 'exit' was failing for me for some reason. The above defaults seem like a good idea, though.</p>\n"}, {'answer_id': 69808, 'author': 'Bruno De Fraine', 'author_id': 6918, 'author_profile': 'https://Stackoverflow.com/users/6918', 'pm_score': 7, 'selected': False, 'text': "<p>That's a fine solution. I just wanted to add</p>\n\n<pre><code>set -e\n</code></pre>\n\n<p>as a rudimentary error mechanism. It will immediately stop your script if a simple command fails. I think this should have been the default behavior: since such errors almost always signify something unexpected, it is not really 'sane' to keep executing the following commands.</p>\n"}, {'answer_id': 182080, 'author': 'yukondude', 'author_id': 726, 'author_profile': 'https://Stackoverflow.com/users/726', 'pm_score': 3, 'selected': False, 'text': '<p>Another consideration is the exit code to return. Just "<code>1</code>" is pretty standard, although there are a handful of <a href="http://tldp.org/LDP/abs/html/exitcodes.html" rel="noreferrer">reserved exit codes that bash itself uses</a>, and that same page argues that user-defined codes should be in the range 64-113 to conform to C/C++ standards.</p>\n\n<p>You might also consider the bit vector approach that <code>mount</code> uses for its exit codes:</p>\n\n<pre><code> 0  success\n 1  incorrect invocation or permissions\n 2  system error (out of memory, cannot fork, no more loop devices)\n 4  internal mount bug or missing nfs support in mount\n 8  user interrupt\n16  problems writing or locking /etc/mtab\n32  mount failure\n64  some mount succeeded\n</code></pre>\n\n<p><code>OR</code>-ing the codes together allows your script to signal multiple simultaneous errors.</p>\n'}, {'answer_id': 185900, 'author': 'Charles Duffy', 'author_id': 14122, 'author_profile': 'https://Stackoverflow.com/users/14122', 'pm_score': 8, 'selected': False, 'text': '<p>Use a trap!</p>\n<pre><code>tempfiles=( )\ncleanup() {\n  rm -f &quot;${tempfiles[@]}&quot;\n}\ntrap cleanup 0\n\nerror() {\n  local parent_lineno=&quot;$1&quot;\n  local message=&quot;$2&quot;\n  local code=&quot;${3:-1}&quot;\n  if [[ -n &quot;$message&quot; ]] ; then\n    echo &quot;Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}&quot;\n  else\n    echo &quot;Error on or near line ${parent_lineno}; exiting with status ${code}&quot;\n  fi\n  exit &quot;${code}&quot;\n}\ntrap \'error ${LINENO}\' ERR\n</code></pre>\n<p>...then, whenever you create a temporary file:</p>\n<pre><code>temp_foo=&quot;$(mktemp -t foobar.XXXXXX)&quot;\ntempfiles+=( &quot;$temp_foo&quot; )\n</code></pre>\n<p>and <code>$temp_foo</code> will be deleted on exit, and the current line number will be printed. (<code>set -e</code> will likewise give you exit-on-error behavior, <A HREF="http://mywiki.wooledge.org/BashFAQ/105" rel="nofollow noreferrer">though it comes with serious caveats</A> and weakens code\'s predictability and portability).</p>\n<p>You can either let the trap call <code>error</code> for you (in which case it uses the default exit code of 1 and no message) or call it yourself and provide explicit values; for instance:</p>\n<pre><code>error ${LINENO} &quot;the foobar failed&quot; 2\n</code></pre>\n<p>will exit with status 2, and give an explicit message.</p>\n<p>Alternatively <code>shopt -s extdebug</code> and give the first lines of the trap a little modification to trap all non-zero exit codes across the board (mind <code>set -e</code> non-error non-zero exit codes):</p>\n<pre><code>error() {\n  local last_exit_status=&quot;$?&quot;\n  local parent_lineno=&quot;$1&quot;\n  local message=&quot;${2:-(no message ($last_exit_status))}&quot;\n  local code=&quot;${3:-$last_exit_status}&quot;\n  # ... continue as above\n}\ntrap \'error ${LINENO}\' ERR\nshopt -s extdebug\n</code></pre>\n<p>This then is also &quot;compatible&quot; with <code>set -eu</code>.</p>\n'}, {'answer_id': 1771722, 'author': 'Michael Nooner', 'author_id': 215602, 'author_profile': 'https://Stackoverflow.com/users/215602', 'pm_score': 4, 'selected': False, 'text': '<p>I prefer something really easy to call. So I use something that looks a little complicated, but is easy to use. I usually just copy-and-paste the code below into my scripts. An explanation follows the code.</p>\n\n<pre><code>#This function is used to cleanly exit any script. It does this displaying a\n# given error message, and exiting with an error code.\nfunction error_exit {\n    echo\n    echo "$@"\n    exit 1\n}\n#Trap the killer signals so that we can exit with a good message.\ntrap "error_exit \'Received signal SIGHUP\'" SIGHUP\ntrap "error_exit \'Received signal SIGINT\'" SIGINT\ntrap "error_exit \'Received signal SIGTERM\'" SIGTERM\n\n#Alias the function so that it will print a message with the following format:\n#prog-name(@line#): message\n#We have to explicitly allow aliases, we do this because they make calling the\n#function much easier (see example).\nshopt -s expand_aliases\nalias die=\'error_exit "Error ${0}(@`echo $(( $LINENO - 1 ))`):"\'\n</code></pre>\n\n<p>I usually put a call to the cleanup function in side the error_exit function, but this varies from script to script so I left it out. The traps catch the common terminating signals and make sure everything gets cleaned up. The alias is what does the real magic. I like to check everything for failure. So in general I call programs in an "if !" type statement. By subtracting 1 from the line number the alias will tell me where the failure occurred. It is also dead simple to call, and pretty much idiot proof. Below is an example (just replace /bin/false with whatever you are going to call).</p>\n\n<pre><code>#This is an example useage, it will print out\n#Error prog-name (@1): Who knew false is false.\nif ! /bin/false ; then\n    die "Who knew false is false."\nfi\n</code></pre>\n'}, {'answer_id': 1877000, 'author': 'Ben Scholbrock', 'author_id': 228321, 'author_profile': 'https://Stackoverflow.com/users/228321', 'pm_score': 5, 'selected': False, 'text': '<p>An equivalent alternative to "set -e" is</p>\n\n<pre><code>set -o errexit\n</code></pre>\n\n<p>It makes the meaning of the flag somewhat clearer than just "-e".</p>\n\n<p>Random addition: to temporarily disable the flag, and return to the default (of continuing execution regardless of exit codes), just use</p>\n\n<pre><code>set +e\necho "commands run here returning non-zero exit codes will not cause the entire script to fail"\necho "false returns 1 as an exit code"\nfalse\nset -e\n</code></pre>\n\n<p>This precludes proper error handling mentioned in other responses, but is quick &amp; effective (just like bash).</p>\n'}, {'answer_id': 6290175, 'author': 'l0b0', 'author_id': 96588, 'author_profile': 'https://Stackoverflow.com/users/96588', 'pm_score': 2, 'selected': False, 'text': '<p><a href="https://github.com/l0b0/tilde/blob/master/scripts/functions.sh" rel="nofollow">This</a> has served me well for a while now. It prints error or warning messages in red, one line per parameter, and allows an optional exit code.</p>\n\n<pre><code># Custom errors\nEX_UNKNOWN=1\n\nwarning()\n{\n    # Output warning messages\n    # Color the output red if it\'s an interactive terminal\n    # @param $1...: Messages\n\n    test -t 1 &amp;&amp; tput setf 4\n\n    printf \'%s\\n\' "$@" &gt;&amp;2\n\n    test -t 1 &amp;&amp; tput sgr0 # Reset terminal\n    true\n}\n\nerror()\n{\n    # Output error messages with optional exit code\n    # @param $1...: Messages\n    # @param $N: Exit code (optional)\n\n    messages=( "$@" )\n\n    # If the last parameter is a number, it\'s not part of the messages\n    last_parameter="${messages[@]: -1}"\n    if [[ "$last_parameter" =~ ^[0-9]*$ ]]\n    then\n        exit_code=$last_parameter\n        unset messages[$((${#messages[@]} - 1))]\n    fi\n\n    warning "${messages[@]}"\n\n    exit ${exit_code:-$EX_UNKNOWN}\n}\n</code></pre>\n'}, {'answer_id': 11564455, 'author': 'Olivier Delrieu', 'author_id': 769749, 'author_profile': 'https://Stackoverflow.com/users/769749', 'pm_score': 3, 'selected': False, 'text': '<p>I use the following trap code, it also allows <strong>errors to be traced through pipes and \'time\' commands</strong></p>\n\n<pre><code>#!/bin/bash\nset -o pipefail  # trace ERR through pipes\nset -o errtrace  # trace ERR through \'time command\' and other functions\nfunction error() {\n    JOB="$0"              # job name\n    LASTLINE="$1"         # line of error occurrence\n    LASTERR="$2"          # error code\n    echo "ERROR in ${JOB} : line ${LASTLINE} with exit code ${LASTERR}"\n    exit 1\n}\ntrap \'error ${LINENO} ${?}\' ERR\n</code></pre>\n'}, {'answer_id': 12414661, 'author': 'Nelson Rodriguez', 'author_id': 1037940, 'author_profile': 'https://Stackoverflow.com/users/1037940', 'pm_score': 2, 'selected': False, 'text': '<p>Not sure if this will be helpful to you, but I modified some of the suggested functions here in order to include the check for the error (exit code from prior command) within it.\nOn each "check" I also pass as a parameter the "message" of what the error is for logging purposes.</p>\n\n<pre><code>#!/bin/bash\n\nerror_exit()\n{\n    if [ "$?" != "0" ]; then\n        log.sh "$1"\n        exit 1\n    fi\n}\n</code></pre>\n\n<p>Now to call it within the same script (or in another one if I use <code>export -f error_exit</code>) I simply write the name of the function and pass a message as parameter, like this:</p>\n\n<pre><code>#!/bin/bash\n\ncd /home/myuser/afolder\nerror_exit "Unable to switch to folder"\n\nrm *\nerror_exit "Unable to delete all files"\n</code></pre>\n\n<p>Using this I was able to create a really robust bash file for some automated process and it will stop in case of errors and notify me (<code>log.sh</code> will do that)</p>\n'}, {'answer_id': 13099228, 'author': 'Luca Borrione', 'author_id': 1032370, 'author_profile': 'https://Stackoverflow.com/users/1032370', 'pm_score': 7, 'selected': False, 'text': '<p>Reading all the answers on this page inspired me a lot.<br>\n<br>\nSo, here\'s my hint:<br>\n<br>\n<strong><em>file content: lib.trap.sh</em></strong></p>\n\n<pre><code>lib_name=\'trap\'\nlib_version=20121026\n\nstderr_log="/dev/shm/stderr.log"\n\n#\n# TO BE SOURCED ONLY ONCE:\n#\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n\nif test "${g_libs[$lib_name]+_}"; then\n    return 0\nelse\n    if test ${#g_libs[@]} == 0; then\n        declare -A g_libs\n    fi\n    g_libs[$lib_name]=$lib_version\nfi\n\n\n#\n# MAIN CODE:\n#\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n\nset -o pipefail  # trace ERR through pipes\nset -o errtrace  # trace ERR through \'time command\' and other functions\nset -o nounset   ## set -u : exit the script if you try to use an uninitialised variable\nset -o errexit   ## set -e : exit the script if any statement returns a non-true return value\n\nexec 2&gt;"$stderr_log"\n\n\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n#\n# FUNCTION: EXIT_HANDLER\n#\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n\nfunction exit_handler ()\n{\n    local error_code="$?"\n\n    test $error_code == 0 &amp;&amp; return;\n\n    #\n    # LOCAL VARIABLES:\n    # ------------------------------------------------------------------\n    #    \n    local i=0\n    local regex=\'\'\n    local mem=\'\'\n\n    local error_file=\'\'\n    local error_lineno=\'\'\n    local error_message=\'unknown\'\n\n    local lineno=\'\'\n\n\n    #\n    # PRINT THE HEADER:\n    # ------------------------------------------------------------------\n    #\n    # Color the output if it\'s an interactive terminal\n    test -t 1 &amp;&amp; tput bold; tput setf 4                                 ## red bold\n    echo -e "\\n(!) EXIT HANDLER:\\n"\n\n\n    #\n    # GETTING LAST ERROR OCCURRED:\n    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\n\n    #\n    # Read last file from the error log\n    # ------------------------------------------------------------------\n    #\n    if test -f "$stderr_log"\n        then\n            stderr=$( tail -n 1 "$stderr_log" )\n            rm "$stderr_log"\n    fi\n\n    #\n    # Managing the line to extract information:\n    # ------------------------------------------------------------------\n    #\n\n    if test -n "$stderr"\n        then        \n            # Exploding stderr on :\n            mem="$IFS"\n            local shrunk_stderr=$( echo "$stderr" | sed \'s/\\: /\\:/g\' )\n            IFS=\':\'\n            local stderr_parts=( $shrunk_stderr )\n            IFS="$mem"\n\n            # Storing information on the error\n            error_file="${stderr_parts[0]}"\n            error_lineno="${stderr_parts[1]}"\n            error_message=""\n\n            for (( i = 3; i &lt;= ${#stderr_parts[@]}; i++ ))\n                do\n                    error_message="$error_message "${stderr_parts[$i-1]}": "\n            done\n\n            # Removing last \':\' (colon character)\n            error_message="${error_message%:*}"\n\n            # Trim\n            error_message="$( echo "$error_message" | sed -e \'s/^[ \\t]*//\' | sed -e \'s/[ \\t]*$//\' )"\n    fi\n\n    #\n    # GETTING BACKTRACE:\n    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\n    _backtrace=$( backtrace 2 )\n\n\n    #\n    # MANAGING THE OUTPUT:\n    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\n\n    local lineno=""\n    regex=\'^([a-z]{1,}) ([0-9]{1,})$\'\n\n    if [[ $error_lineno =~ $regex ]]\n\n        # The error line was found on the log\n        # (e.g. type \'ff\' without quotes wherever)\n        # --------------------------------------------------------------\n        then\n            local row="${BASH_REMATCH[1]}"\n            lineno="${BASH_REMATCH[2]}"\n\n            echo -e "FILE:\\t\\t${error_file}"\n            echo -e "${row^^}:\\t\\t${lineno}\\n"\n\n            echo -e "ERROR CODE:\\t${error_code}"             \n            test -t 1 &amp;&amp; tput setf 6                                    ## white yellow\n            echo -e "ERROR MESSAGE:\\n$error_message"\n\n\n        else\n            regex="^${error_file}\\$|^${error_file}\\s+|\\s+${error_file}\\s+|\\s+${error_file}\\$"\n            if [[ "$_backtrace" =~ $regex ]]\n\n                # The file was found on the log but not the error line\n                # (could not reproduce this case so far)\n                # ------------------------------------------------------\n                then\n                    echo -e "FILE:\\t\\t$error_file"\n                    echo -e "ROW:\\t\\tunknown\\n"\n\n                    echo -e "ERROR CODE:\\t${error_code}"\n                    test -t 1 &amp;&amp; tput setf 6                            ## white yellow\n                    echo -e "ERROR MESSAGE:\\n${stderr}"\n\n                # Neither the error line nor the error file was found on the log\n                # (e.g. type \'cp ffd fdf\' without quotes wherever)\n                # ------------------------------------------------------\n                else\n                    #\n                    # The error file is the first on backtrace list:\n\n                    # Exploding backtrace on newlines\n                    mem=$IFS\n                    IFS=\'\n                    \'\n                    #\n                    # Substring: I keep only the carriage return\n                    # (others needed only for tabbing purpose)\n                    IFS=${IFS:0:1}\n                    local lines=( $_backtrace )\n\n                    IFS=$mem\n\n                    error_file=""\n\n                    if test -n "${lines[1]}"\n                        then\n                            array=( ${lines[1]} )\n\n                            for (( i=2; i&lt;${#array[@]}; i++ ))\n                                do\n                                    error_file="$error_file ${array[$i]}"\n                            done\n\n                            # Trim\n                            error_file="$( echo "$error_file" | sed -e \'s/^[ \\t]*//\' | sed -e \'s/[ \\t]*$//\' )"\n                    fi\n\n                    echo -e "FILE:\\t\\t$error_file"\n                    echo -e "ROW:\\t\\tunknown\\n"\n\n                    echo -e "ERROR CODE:\\t${error_code}"\n                    test -t 1 &amp;&amp; tput setf 6                            ## white yellow\n                    if test -n "${stderr}"\n                        then\n                            echo -e "ERROR MESSAGE:\\n${stderr}"\n                        else\n                            echo -e "ERROR MESSAGE:\\n${error_message}"\n                    fi\n            fi\n    fi\n\n    #\n    # PRINTING THE BACKTRACE:\n    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\n\n    test -t 1 &amp;&amp; tput setf 7                                            ## white bold\n    echo -e "\\n$_backtrace\\n"\n\n    #\n    # EXITING:\n    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\n\n    test -t 1 &amp;&amp; tput setf 4                                            ## red bold\n    echo "Exiting!"\n\n    test -t 1 &amp;&amp; tput sgr0 # Reset terminal\n\n    exit "$error_code"\n}\ntrap exit_handler EXIT                                                  # ! ! ! TRAP EXIT ! ! !\ntrap exit ERR                                                           # ! ! ! TRAP ERR ! ! !\n\n\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n#\n# FUNCTION: BACKTRACE\n#\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n\nfunction backtrace\n{\n    local _start_from_=0\n\n    local params=( "$@" )\n    if (( "${#params[@]}" &gt;= "1" ))\n        then\n            _start_from_="$1"\n    fi\n\n    local i=0\n    local first=false\n    while caller $i &gt; /dev/null\n    do\n        if test -n "$_start_from_" &amp;&amp; (( "$i" + 1   &gt;= "$_start_from_" ))\n            then\n                if test "$first" == false\n                    then\n                        echo "BACKTRACE IS:"\n                        first=true\n                fi\n                caller $i\n        fi\n        let "i=i+1"\n    done\n}\n\nreturn 0\n</code></pre>\n\n<p><br>\n<br>\n<strong>Example of usage:</strong><br>\nfile content: trap-test.sh</p>\n\n<pre><code>#!/bin/bash\n\nsource \'lib.trap.sh\'\n\necho "doing something wrong now .."\necho "$foo"\n\nexit 0\n</code></pre>\n\n<p><br>\nRunning:</p>\n\n<pre><code>bash trap-test.sh\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>doing something wrong now ..\n\n(!) EXIT HANDLER:\n\nFILE:       trap-test.sh\nLINE:       6\n\nERROR CODE: 1\nERROR MESSAGE:\nfoo:   unassigned variable\n\nBACKTRACE IS:\n1 main trap-test.sh\n\nExiting!\n</code></pre>\n\n<p><br>\nAs you can see from the screenshot below, the output is colored and the error message comes in the used language.<br>\n<br>\n<img src="https://i.stack.imgur.com/0uBOL.jpg" alt="enter image description here"></p>\n'}, {'answer_id': 18118450, 'author': 'Orwellophile', 'author_id': 912236, 'author_profile': 'https://Stackoverflow.com/users/912236', 'pm_score': 2, 'selected': False, 'text': '<p>This trick is useful for missing commands or functions.  The name of the missing function (or executable) will be passed in $_ </p>\n\n<pre><code>function handle_error {\n    status=$?\n    last_call=$1\n\n    # 127 is \'command not found\'\n    (( status != 127 )) &amp;&amp; return\n\n    echo "you tried to call $last_call"\n    return\n}\n\n# Trap errors.\ntrap \'handle_error "$_"\' ERR\n</code></pre>\n'}, {'answer_id': 30019669, 'author': 'niieani', 'author_id': 595157, 'author_profile': 'https://Stackoverflow.com/users/595157', 'pm_score': 4, 'selected': False, 'text': '<p>Inspired by the ideas presented here, I have developed a readable and convenient way to handle errors in bash scripts in my <a href="https://github.com/niieani/bash-oo-framework" rel="noreferrer">bash boilerplate project</a>. </p>\n\n<p>By simply sourcing the library, you get the following out of the box (i.e.  it will halt execution on any error, as if using <code>set -e</code> thanks to a <code>trap</code> on <code>ERR</code> and some <em>bash-fu</em>):</p>\n\n<p><img src="https://i.stack.imgur.com/UJhwZ.png" alt="bash-oo-framework error handling"></p>\n\n<p>There are some extra features that help handle errors, such as <strong>try and catch</strong>, or the <strong>throw</strong> keyword, that allows you to break execution at a point to see the backtrace. Plus, if the terminal supports it, it spits out powerline emojis, colors parts of the output for great readability, and underlines the method that caused the exception in the context of the line of code.</p>\n\n<p>The downside is - it\'s not portable - the code works in bash, probably >= 4 only (but I\'d imagine it could be ported with some effort to bash 3).</p>\n\n<p>The code is separated into multiple files for better handling, but I was inspired by the backtrace idea from <a href="https://stackoverflow.com/questions/64786/error-handling-in-bash/13099228#13099228">the answer above by Luca Borrione</a>. </p>\n\n<p>To read more or take a look at the source, see GitHub:</p>\n\n<p><a href="https://github.com/niieani/bash-oo-framework#error-handling-with-exceptions-and-throw" rel="noreferrer">https://github.com/niieani/bash-oo-framework#error-handling-with-exceptions-and-throw</a></p>\n'}, {'answer_id': 34726287, 'author': 'skozin', 'author_id': 804678, 'author_profile': 'https://Stackoverflow.com/users/804678', 'pm_score': 1, 'selected': False, 'text': '\n\n<p>Using trap is not always an option. For example, if you\'re writing some kind of re-usable function that needs error handling and that can be called from any script (after sourcing the file with helper functions), that function cannot assume anything about exit time of the outer script, which makes using traps very difficult. Another disadvantage of using traps is bad composability, as you risk overwriting previous trap that might be set earlier up in the caller chain.</p>\n\n<p>There is a little trick that can be used to do proper error handling without traps. As you may already know from other answers, <code>set -e</code> doesn\'t work inside commands if you use <code>||</code> operator after them, even if you run them in a subshell; e.g., this wouldn\'t work:</p>\n\n<pre class="lang-sh prettyprint-override"><code>#!/bin/sh\n\n# prints:\n#\n# --&gt; outer\n# --&gt; inner\n# ./so_1.sh: line 16: some_failed_command: command not found\n# &lt;-- inner\n# &lt;-- outer\n\nset -e\n\nouter() {\n  echo \'--&gt; outer\'\n  (inner) || {\n    exit_code=$?\n    echo \'--&gt; cleanup\'\n    return $exit_code\n  }\n  echo \'&lt;-- outer\'\n}\n\ninner() {\n  set -e\n  echo \'--&gt; inner\'\n  some_failed_command\n  echo \'&lt;-- inner\'\n}\n\nouter\n</code></pre>\n\n<p>But <code>||</code> operator is needed to prevent returning from the outer function before cleanup. The trick is to run the inner command in background, and then immediately wait for it. The <code>wait</code> builtin will return the exit code of the inner command, and now you\'re using <code>||</code> after <code>wait</code>, not the inner function, so <code>set -e</code> works properly inside the latter:</p>\n\n<pre class="lang-sh prettyprint-override"><code>#!/bin/sh\n\n# prints:\n#\n# --&gt; outer\n# --&gt; inner\n# ./so_2.sh: line 27: some_failed_command: command not found\n# --&gt; cleanup\n\nset -e\n\nouter() {\n  echo \'--&gt; outer\'\n  inner &amp;\n  wait $! || {\n    exit_code=$?\n    echo \'--&gt; cleanup\'\n    return $exit_code\n  }\n  echo \'&lt;-- outer\'\n}\n\ninner() {\n  set -e\n  echo \'--&gt; inner\'\n  some_failed_command\n  echo \'&lt;-- inner\'\n}\n\nouter\n</code></pre>\n\n<p>Here is the generic function that builds upon this idea. It should work in all POSIX-compatible shells if you remove <code>local</code> keywords, i.e. replace all <code>local x=y</code> with just <code>x=y</code>:</p>\n\n<pre class="lang-sh prettyprint-override"><code># [CLEANUP=cleanup_cmd] run cmd [args...]\n#\n# `cmd` and `args...` A command to run and its arguments.\n#\n# `cleanup_cmd` A command that is called after cmd has exited,\n# and gets passed the same arguments as cmd. Additionally, the\n# following environment variables are available to that command:\n#\n# - `RUN_CMD` contains the `cmd` that was passed to `run`;\n# - `RUN_EXIT_CODE` contains the exit code of the command.\n#\n# If `cleanup_cmd` is set, `run` will return the exit code of that\n# command. Otherwise, it will return the exit code of `cmd`.\n#\nrun() {\n  local cmd="$1"; shift\n  local exit_code=0\n\n  local e_was_set=1; if ! is_shell_attribute_set e; then\n    set -e\n    e_was_set=0\n  fi\n\n  "$cmd" "$@" &amp;\n\n  wait $! || {\n    exit_code=$?\n  }\n\n  if [ "$e_was_set" = 0 ] &amp;&amp; is_shell_attribute_set e; then\n    set +e\n  fi\n\n  if [ -n "$CLEANUP" ]; then\n    RUN_CMD="$cmd" RUN_EXIT_CODE="$exit_code" "$CLEANUP" "$@"\n    return $?\n  fi\n\n  return $exit_code\n}\n\n\nis_shell_attribute_set() { # attribute, like "x"\n  case "$-" in\n    *"$1"*) return 0 ;;\n    *)    return 1 ;;\n  esac\n}\n</code></pre>\n\n<p>Example of usage:</p>\n\n<pre class="lang-sh prettyprint-override"><code>#!/bin/sh\nset -e\n\n# Source the file with the definition of `run` (previous code snippet).\n# Alternatively, you may paste that code directly here and comment the next line.\n. ./utils.sh\n\n\nmain() {\n  echo "--&gt; main: $@"\n  CLEANUP=cleanup run inner "$@"\n  echo "&lt;-- main"\n}\n\n\ninner() {\n  echo "--&gt; inner: $@"\n  sleep 0.5; if [ "$1" = \'fail\' ]; then\n    oh_my_god_look_at_this\n  fi\n  echo "&lt;-- inner"\n}\n\n\ncleanup() {\n  echo "--&gt; cleanup: $@"\n  echo "    RUN_CMD = \'$RUN_CMD\'"\n  echo "    RUN_EXIT_CODE = $RUN_EXIT_CODE"\n  sleep 0.3\n  echo \'&lt;-- cleanup\'\n  return $RUN_EXIT_CODE\n}\n\nmain "$@"\n</code></pre>\n\n<p>Running the example:</p>\n\n<pre class="lang-sh prettyprint-override"><code>$ ./so_3 fail; echo "exit code: $?"\n\n--&gt; main: fail\n--&gt; inner: fail\n./so_3: line 15: oh_my_god_look_at_this: command not found\n--&gt; cleanup: fail\n    RUN_CMD = \'inner\'\n    RUN_EXIT_CODE = 127\n&lt;-- cleanup\nexit code: 127\n\n$ ./so_3 pass; echo "exit code: $?"\n\n--&gt; main: pass\n--&gt; inner: pass\n&lt;-- inner\n--&gt; cleanup: pass\n    RUN_CMD = \'inner\'\n    RUN_EXIT_CODE = 0\n&lt;-- cleanup\n&lt;-- main\nexit code: 0\n</code></pre>\n\n<p>The only thing that you need to be aware of when using this method is that all modifications of Shell variables done from the command you pass to <code>run</code> will not propagate to the calling function, because the command runs in a subshell.</p>\n'}, {'answer_id': 41852435, 'author': 'xarxziux', 'author_id': 5463687, 'author_profile': 'https://Stackoverflow.com/users/5463687', 'pm_score': 2, 'selected': False, 'text': '<p>This function has been serving me rather well recently:</p>\n\n<pre><code>action () {\n    # Test if the first parameter is non-zero\n    # and return straight away if so\n    if test $1 -ne 0\n    then\n        return $1\n    fi\n\n    # Discard the control parameter\n    # and execute the rest\n    shift 1\n    "$@"\n    local status=$?\n\n    # Test the exit status of the command run\n    # and display an error message on failure\n    if test ${status} -ne 0\n    then\n        echo Command \\""$@"\\" failed &gt;&amp;2\n    fi\n\n    return ${status}\n}\n</code></pre>\n\n<p>You call it by appending 0 or the last return value to the name of the command to run, so you can chain commands without having to check for error values.  With this, this statement block:</p>\n\n<pre><code>command1 param1 param2 param3...\ncommand2 param1 param2 param3...\ncommand3 param1 param2 param3...\ncommand4 param1 param2 param3...\ncommand5 param1 param2 param3...\ncommand6 param1 param2 param3...\n</code></pre>\n\n<p>Becomes this:</p>\n\n<pre><code>action 0 command1 param1 param2 param3...\naction $? command2 param1 param2 param3...\naction $? command3 param1 param2 param3...\naction $? command4 param1 param2 param3...\naction $? command5 param1 param2 param3...\naction $? command6 param1 param2 param3...\n\n&lt;&lt;&lt;Error-handling code here&gt;&gt;&gt;\n</code></pre>\n\n<p>If any of the commands fail, the error code is simply passed to the end of the block.  I find it useful when you don\'t want subsequent commands to execute if an earlier one failed, but you also don\'t want the script to exit straight away (for example, inside a loop).</p>\n'}, {'answer_id': 68857236, 'author': 'NITHIN KIRTHICK', 'author_id': 13744498, 'author_profile': 'https://Stackoverflow.com/users/13744498', 'pm_score': 1, 'selected': False, 'text': '<p>Sometimes <code>set -e</code> , <code>trap ERR</code> ,<code>set -o</code> <code>,set -o pipefail</code> and <code>set -o errtrace</code> not work properly because they attempt to add <strong>automatic error detection</strong> to the shell. This does not work well in practice.</p>\n<p>In my opinion, instead of using <code>set -e</code> and other stuffs, you should write your own error checking code. If you wise to use <code>set -e</code>, be aware of potential gotchas.</p>\n<p>To avoid Error while running the code you can use <code>exec 1&gt;/dev/null</code> or <code>exec 2&gt;/dev/null</code><br />\n<code>/dev/null</code> in Linux is a null device file. This will discard anything written to it and will return EOF on reading. you can use this at end of the command</p>\n<p>For <code>try/catch</code> you can use <code>&amp;&amp;</code> or <code>||</code> to achieve Similar behaviour\nuse can use &amp;&amp; like this</p>\n<pre><code>{ # try\n\n    command &amp;&amp;\n    # your command \n\n} || { \n    # catch exception \n}\n</code></pre>\n<p>or you can use <code>if else</code> :</p>\n<pre><code>if [[ Condition ]]; then\n    # if true\nelse\n    # if false\nfi\n</code></pre>\n<p><code>$?</code> show output of the last command ,it return 1 or 0</p>\n'}]
['https://Stackoverflow.com/questions/64786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']