Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to exit from a Linux terminal if a command failed?
It is a common scenario that certain commands might fail for various reasons − differences between GNU and BSD versions of core utilities, logical errors, or missing dependencies. When commands fail, you may want to terminate the process or exit the terminal without manually pressing CTRL + C. Here are several methods to handle command failures gracefully.
Using bash exit command with ||
The logical OR operator (||) allows you to execute a command only if the previous command fails. This is useful when you want to exit the terminal immediately upon command failure.
my_command || { echo 'my_command failed!' ; exit 1; }
This command ensures the terminal exits with status code 1 if my_command fails. The curly braces { } group the echo and exit statements together.
Practical Example
wget https://example.com/file.txt || { echo 'Download failed!' ; exit 1; }
Using Exit Status Variable $?
The $? variable contains the exit status of the last executed command. A value of 0 indicates success, while non-zero values indicate failure.
my_command if [ $? -eq 0 ]; then echo "Command executed successfully" else echo "Command failed with exit code $?" exit 1 fi
This approach gives you more control over error handling and allows you to display specific error messages or perform cleanup operations before exiting.
Using set -e
The set -e option enables exit-on-error mode in bash scripts. When enabled, the script automatically exits if any command returns a non-zero exit status.
#!/bin/bash set -e echo "Starting script..." my_command another_command echo "All commands completed successfully"
This is particularly useful for bash scripts where you want to ensure all commands execute successfully before proceeding.
Comparison of Methods
| Method | Use Case | Advantages | Disadvantages |
|---|---|---|---|
| || operator | Single command failure | Concise, immediate exit | Limited error handling |
| $? variable | Custom error handling | Flexible, detailed control | More verbose |
| set -e | Bash scripts | Automatic error detection | May exit unexpectedly |
Additional Options
You can combine set -e with set -o pipefail to catch failures in pipeline commands:
set -eo pipefail command1 | command2 | command3
For more graceful error handling, use trap to execute cleanup code before exiting:
trap 'echo "Script failed at line $LINENO"' ERR set -e
Conclusion
These methods provide different approaches to handle command failures in Linux terminals. Use || for quick single-command error handling, $? for detailed error control, and set -e for automatic script termination on any command failure.
