What is the purpose of $?

The $? variable in a shell script or command line context is used to retrieve the exit status of the last executed command.

Purpose of $?

  • Exit Status: It provides a way to check whether the previous command was successful or if it encountered an error. An exit status of 0 typically indicates success, while any non-zero value indicates an error or failure.

Example Usage

Here’s a simple example to illustrate its use:

# Run a command
ls /some/directory

# Check the exit status
if [ $? -eq 0 ]; then
    echo "Command succeeded."
else
    echo "Command failed."
fi

In this example:

  • The ls command attempts to list the contents of /some/directory.
  • After executing ls, $? is checked. If it equals 0, it prints "Command succeeded." If it’s non-zero, it prints "Command failed."

Summary

Using $? is essential for error handling in scripts, allowing you to make decisions based on the success or failure of commands.

0 Comments

no data
Be the first to share your comment!