
- Kali Linux Tutorial
- Kali Linux - Home
- Installation & Configuration
- Information Gathering Tools
- Vulnerability Analyses Tools
- Kali Linux - Wireless Attacks
- Website Penetration Testing
- Kali Linux - Exploitation Tools
- Kali Linux - Forensics Tools
- Kali Linux - Social Engineering
- Kali Linux - Stressing Tools
- Kali Linux - Sniffing & Spoofing
- Kali Linux - Password Cracking Tools
- Kali Linux - Maintaining Access
- Kali Linux - Reverse Engineering
- Kali Linux - Reporting Tools
- Kali Linux Useful Resources
- Kali Linux - Quick Guide
- Kali Linux - Useful Resources
- Kali Linux - Discussion
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 Articles
- How to exit from a Python if clause?
- 10 Cool Command Line Tools For Your Linux Terminal
- How to Test your Broadband Speed from Linux Terminal
- How to output colored text to a Linux terminal?
- How to download a website page on Linux terminal?
- Bash break How to Exit From a Loop
- Sending Emails From Terminal In Linux
- How to Clear Linux terminal screen?
- How to Record Linux Terminal Sessions?
- How to exit from Python using a Tkinter Button?
- How to create a new directory in Linux using the terminal?
- How to use a pipe with Linux find command?
- How to Run a Command Multiple Times in Linux?
- How to Get the Path of a Linux Command?
- How to Save Command Output to a File in Linux?
