Coding⏱️ 2 min read📅 2026-05-31

How to Fix: How to exit if a command failed?

Print a message and exit script if command fails.

Quick Answer: Use the || operator to execute the echo statement only if my_command succeeds, e.g. my_command || (echo 'my_command failed; exit')

To exit a shell script if a command fails, you can use the exit or return statement. The correct syntax for exiting the script after executing a command is:

my_command && ( echo 'my_command failed'; exit )

This will execute the echo command if my_command succeeds, and then immediately exit the script. If my_command fails, the exit statement will be executed.

🔧 Proven Troubleshooting Steps

Method 1: Using exit

  1. Step 1: Use the exit statement after executing a command that may fail.

Method 2: Using return

  1. Step 1: Use the return statement with a non-zero exit status to indicate failure.

🎯 Final Words

By following these steps, you can ensure that your shell script exits gracefully if a command fails. Remember to always test your scripts thoroughly to catch any errors.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions