Bash basic error handling

Just like your daily programming language, bash can handle errors as well. Handling errors or detecting them and handle them once detected is important when developing a bash script. There are some technique used by bash experts but I found two of them being very useful.

Using logical AND

For simple two-step commands, you can use the && operator so that the second will be executed only when the first command returns success. Example below:

cd $WORKING_DIR && svn up --non-interactive --username "$SVN_USERNAME" --password 

Based on the example above, we tried to change directory to $WORKING_DIR and execute svn up. In case $WORKING_DIR does not exists, it will not execute the second command as the first command already fails.

Reading the error return code

For a more programmable approach, reading the error return code is better. Most programs are programmed to return 0 for a success. Below is the more complex version of our first example.

for i in "${R3_WORKING_COPIES[@]}"
    echo "Working on $TARGET_DIR"
    cd $TARGET_DIR
    # Do not proceed with svn up if directory does not exists
    if [ $? -eq 0 ]; then
        svn up --non-interactive --username "$SVN_USERNAME" --password "$SVN_PASSWORD"
        if [ $? -ne 0 ]; then
            # Possible authentication failure, do not proceed with the rest
            # to avoid being locked out

1 thought on “Bash basic error handling”

  1. It would be better to use a variable for the exit code especially if you still nee to have that on other commands.

Leave a reply

Your email address will not be published. Required fields are marked *