Bash

How to exit if a command failed duplicate

25 September 2026 · 4 min read

How to exit if a command failed duplicate

Ensuring a script stops executing after a command failure is crucial for maintaining system integrity and preventing unintended consequences. Whether you’re a seasoned system administrator crafting complex automation scripts or a beginner just starting with shell scripting, understanding how to gracefully handle errors is fundamental. This article dives deep into various techniques and best practices for exiting a script when a command fails, empowering you to write robust and reliable scripts.

Using the exit Command

The simplest way to halt a script upon encountering an error is using the exit command. By convention, a non-zero exit code signifies an error. This allows other scripts or processes to understand the script’s outcome.

For example:

command || exit 1

This line attempts to execute command. If it fails (returns a non-zero exit code), the || (OR) operator triggers the exit 1 command, halting the script and returning the exit code 1.

Leveraging set -e for Automatic Exit

The set -e option (also known as set -o errexit) provides a more comprehensive approach to error handling. When this option is enabled, the script will automatically exit if any command returns a non-zero exit code, eliminating the need for explicit exit statements after each command.

Example:

!/bin/bash set -e command1 command2 command3 

In this script, if command1, command2, or command3 fails, the script will terminate immediately.

Handling Specific Commands with trap

The trap command offers fine-grained control over error handling. It allows you to specify a command or a set of commands to be executed when a specific signal is received, including the ERR signal, which is triggered by a command failure.

Example:

trap 'echo "Error occurred"; exit 1' ERR command1 command2 

If either command1 or command2 fails, the specified trap will execute, printing an error message and exiting the script.

Best Practices for Robust Error Handling

Combining these techniques with other best practices further enhances script reliability. Consider using a dedicated error handling function to centralize error logging and cleanup operations. This can improve code maintainability and readability.

Example:

handle_error() { echo "An error occurred: $1" Perform cleanup operations exit 1 } trap 'handle_error "Command failed"' ERR command1 command2 
  • Always check the exit status of commands using $?.
  • Use descriptive error messages to facilitate debugging.

For further reading on bash scripting and error handling, refer to the Bash Manual.

Using Conditional Statements for Complex Logic

For more complex scenarios, use conditional statements (if/then/else) to handle specific error conditions differently. This allows for more nuanced responses based on the nature of the failure.

if command; then echo "Command successful" else echo "Command failed" exit 1 fi 
  1. Plan your error handling strategy before writing your script.
  2. Test your scripts thoroughly, including various error scenarios.
  3. Document your error handling logic for maintainability.

See also this related article.

[Infographic about different exit strategies]

FAQ

Q: What is the significance of the exit code?

A: The exit code allows other programs or scripts to determine if the script executed successfully (exit code 0) or encountered an error (non-zero exit code). This is essential for automation and scripting workflows.

By implementing these techniques, you can create robust and dependable scripts that gracefully handle errors, ensuring smooth operation and preventing unintended side effects. Understanding these different approaches empowers you to choose the best strategy for your specific scripting needs. Remember to always prioritize clear error messages and comprehensive testing for reliable and maintainable code. Explore resources like LinuxConfig.org and Stack Overflow for more advanced techniques and community support. Finally, delve deeper into the nuances of scripting with the extensive documentation available at The Linux Documentation Project. This will further refine your scripting skills and enable you to handle complex error scenarios effectively.

Question & Answer :

I am a noob in shell-scripting. I want to print a message and exit my script if a command fails. I've tried:
my_command && (echo 'my_command failed; exit) 

but it does not work. It keeps executing the instructions following this line in the script. I’m using Ubuntu and bash.

Try:

my_command || { echo 'my_command failed' ; exit 1; } 

Four changes:

  • Change && to ||
  • Use { } in place of ( )
  • Introduce ; after exit and
  • spaces after { and before }

Since you want to print the message and exit only when the command fails ( exits with non-zero value) you need a || not an &&.

cmd1 && cmd2 

will run cmd2 when cmd1 succeeds(exit value 0). Where as

cmd1 || cmd2 

will run cmd2 when cmd1 fails(exit value non-zero).

Using ( ) makes the command inside them run in a sub-shell and calling a exit from there causes you to exit the sub-shell and not your original shell, hence execution continues in your original shell.

To overcome this use { }

The last two changes are required by bash.