How to check if a command succeeded in Linux?

In this tutorial, we'll explore various methods of checking if a command succeeded focusing primarily on Unix-based systems.

How to check if a command succeeded in Linux?

Oh the terminal, we are all familiar with the Linux terminal. Maybe a little too when. When executing commands in the Linux terminal, you may come across instances where you need to determine whether a command executed successfully.

This is especially useful in automated commands such as bash scripts or cron jobs where the execution of a previous command can impact the execution of the rest of the program.

Checking If a Command Succeeded in Unix-like Systems

Unix-like systems such as Linux and MacOS, use a mechanism called exit status to indicate whether a command has succeeded or not.

The exit status is an integer value where 0 indicates success, and any other number between 1 and 255 indicates a failure. This status is stored in a special variable known as $?

Consider the examples below that demonstrates the usage of this variable.

touch test.txt
echo $?

In the above example, the touch command creates a new file named test.txt.

We then use the echo $? command then prints out the exit status of the touch command. If the file is successfully created, echo $? will output 0.

This mechanism can be very useful in shell scripts. For instance, you can perform different actions depending on whether a command succeeds or fails.

Consider the example shell script that uses the $? variable:

#!/bin/bash
touch test.txt

# Check if it succeeded
if [ $? -eq 0 ]
then
  echo "The command succeeded."
else
  echo "The command failed."
fi

In the example, we start by attempting to create a file with the specified name. If the command succeeds, it will print the message corresponding to the error.

As you can guess, you can expand this feature to ensure more complex logic and error-handling mechanisms.

Conclusion

In this tutorial, we explored how you can check whether a previous command executed successfully in Linux and other Unix-base systems.

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.