bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Error Handling with bash script


From: Lenga, Yair
Subject: Error Handling with bash script
Date: Mon, 24 May 2010 08:35:20 -0400

Hi,

I would like to propose an improvement to the bash error handling: Add 
flag/option "err_return", that will cause a user defined shell functions to 
immediately return, when a simple command will return a non-zero status code.

The behavior is similar to the existing '-e', but is different in the following 
case. Under current bash, the "Abort On Error" logic is suspended if the 
command is executed under "if", "while", "||" or similar. It will make it 
possible to implement much better error handling for scripts that involve user 
defined functions.

Consider the following simple example:

#! /bin/sh
Function f1 {
      cp /new/data /current/data
        step1
        step2
        step3
}

f1 ...

The major issue is that if the /new/data file is missing, or can not be copied 
into the /current/data, processing will continue. Same for failures in 
following steps.

Adding error handling (that will capture missing /new/data, or processing 
errors in step1/2/3), to this script can be done in two ways:

1 - Modifying each functions/script:
Function f1 {
      cp /new/data /current/data || return 1
        step1                      || return 1
        step2                      || return 1
        step3                      || return 1
}

2 - Adding 'set -e' (or the equivalent -oerrexit)

The second approach require significantly less effort, especially if there are 
large number of scripts/functions. The first approach is not feasible if the 
code can not be modified (e.g., code that is used by many scripts that will 
need to be retested, or third-party code).

The problem with the second approach is that the 'errexit' is disabled if the 
command function is used under "while", "if", "||" or similar.

For example, the following will re-establish the bad behavior, where step1 is 
executed even if /new/data is missing:

    if f1 ... ; then
      echo "OK"
        do_more
    else
      echo "Problem"
    fi

The new 'err_return' should address this problem. It will cause 'f1' to return 
immediately (with non-zero return code), if the 'cp' fail, without executing 
the following step1/2/3.

I believe that adding this option will make it much easier to write reliable 
scripts that can properly handle many common error conditions.

Yair Lenga
Yair.lenga@citi.com



reply via email to

[Prev in Thread] Current Thread [Next in Thread]