How to get the exit status of a command in a shell script?

0403

Getting the Exit Status of a Command in a Shell Script

In shell scripting, the exit status of a command is a crucial piece of information that can be used to determine the success or failure of a command's execution. The exit status is a numeric value returned by the command, where a value of 0 typically indicates success, and any non-zero value indicates some form of failure.

Accessing the Exit Status

To access the exit status of the most recently executed command, you can use the special variable $? in your shell script. This variable will contain the exit status of the last command that was executed.

Here's an example:

# Execute a command
ls /path/to/non-existent/directory
# Check the exit status
echo "The exit status is: $?"

In this example, the ls command will fail because the directory does not exist, and the exit status will be a non-zero value (typically 1). The echo statement will then display the exit status.

Using the Exit Status in Conditional Statements

The exit status can be used in conditional statements, such as if-then-else blocks, to determine the next course of action in your script. This allows you to write more robust and error-handling scripts.

Here's an example:

# Execute a command
cp /path/to/source/file /path/to/destination/file
# Check the exit status
if [ $? -eq 0 ]; then
    echo "File copy successful!"
else
    echo "File copy failed!"
fi

In this example, the cp command is executed, and the exit status is checked using an if statement. If the exit status is 0 (success), a message is printed indicating that the file copy was successful. If the exit status is non-zero (failure), a message is printed indicating that the file copy failed.

Mermaid Diagram: Accessing the Exit Status

graph LR A[Execute Command] --> B{Exit Status} B -->|0 (Success)| C[Continue Script] B -->|Non-zero (Failure)| D[Handle Error]

This diagram illustrates the process of accessing the exit status of a command and using it to determine the next steps in the script.

By understanding how to access and use the exit status of commands, you can write more robust and reliable shell scripts that can handle errors and failures gracefully.

0 Comments

no data
Be the first to share your comment!