Little Girl's Mostly Linux Blog

ExitOnError

Exit on error

This page was last updated on April 4, 2012.

Here are a couple of ways to get a script to exit on error if a command fails to run.

Integer test

  • This is an integer test, which means it looks for a specific integer. In this example, the zero integer is used. This example will attempt to run COMMAND. Since COMMAND should exit with a value of zero if it succeeds and non-zero if it fails, you can check what the exit value is and use the value to determine what happens next in your script:
  • COMMAND
    if [ "$?" -ne "0" ]; then
    	echo "FAILURE MESSAGE";
    else
    	echo "SUCCESS MESSAGE";
    fi
    
    • Explanation: Run this command (COMMAND). If the exit value of the command ($?) does not equal (-ne) zero (0) then tell me about it (echo "FAILURE MESSAGE") and exit the script entirely (exit 1). Otherwise (else), tell me it worked (echo "SUCCESS MESSAGE").
    • Example using ls as the command:
    • ls
      if [ "$?" -ne "0" ]; then
      	echo "Failed - aborting script!";
      else
      	echo "Success!";
      fi
      

String expression test

  • This is a string expression test, which means it looks for a specific string. In this example, the zero string is used. This example will attempt to run COMMAND. Since COMMAND should exit with a value of zero if it succeeds and non-zero if it fails, you can check what the exit value is and use the value to determine what happens next in your script:
  • COMMAND
    if [ $? != "0" ] ; then
    	echo "FAILURE MESSAGE";
    	exit 1;
    else
    	echo "SUCCESS MESSAGE";
    fi
    
    • Explanation: Run this command (COMMAND). If the exit value of the command ($?) does not (!) equal (=) zero (0) then tell me about it (echo "FAILURE MESSAGE") and exit the script entirely (exit 1). Otherwise (else), tell me it worked (echo "SUCCESS MESSAGE").
    • Example using ls as the command:
    • ls
      if [ $? != "0" ] ; then
      	echo "Failed - aborting script!";
      	exit 1;
      else
      	echo "Success!";
      fi
      


Obligatory Happy Ending

And they all lived happily ever after. The end.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: WordPress Classic. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.