
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to exit from a Linux terminal if a command failed?
It is a common scenario that certain commands that we write might fail for some reason. The reasons can be many, it can either be because of the difference between the GNU and BSD version of the core utils, or simply because there’s something logically wrong. In such a case, if we want to terminate the process without having to make use of the explicit technique of CTRL + C then we have a couple of different options.
Using bash exit command with ||
Let’s say that we have a certain command my_command that is running perfectly on Ubuntu but on Mac OS X, and you want to make sure that if it fails for some particular reason, then the process should be terminated and the terminal should exit.
In that case, we can make use of the command shown below.
Command
my_command || { echo 'my_command isn't working!' ; exit 1; }
This command will make sure that the terminal exits if and only if the command isn’t working.
Using $
Another command that one can make use of is shown below.
Command
my_command if [ $? -eq 0 ] then echo "it works perfectly" else echo "it isn't working" fi
In the above command, we are making use of the fact that if the command returns a non-zero exit code, then we echo it, and then we can exit from the terminal.
Using set -e
If you are running the command using a bash script, then you can insert the following command at the top of your script.
Command
set -e
Putting the above command on top of your bash script will cause the script to exit if any commands return a non-zero exit code.
- Related Questions & Answers
- How to exit from a Python if clause?
- How to output colored text to a Linux terminal?
- How to Test your Broadband Speed from Linux Terminal
- How to download a website page on Linux terminal?
- How to create a new directory in Linux using the terminal?
- How to use a pipe with Linux find command?
- Generating a SHA-256 hash from the Linux command line
- How to exit from Python using a Tkinter Button?
- How to use rainbow colors in linux terminal
- How to do simple Arithmetic on Linux Terminal?
- How to decorate your Linux Terminal using Shell?
- How to Save Command Output to a File in Linux?
- How to Create a File in the Linux/Unix system using terminal?
- How to Install a Software on Linux Using Yum Command?
- How to Find Linux Server Geographic Location in Terminal?