How to use exit code to read from terminal, from script and with logical operators
Last Updated :
20 Sep, 2024
Scripting is an important part of automation in Linux and it is one of the key tools every system administrators use to manage day-to-day activities like taking backups, adding/removing users/groups, updating/removing packages, etc. Since bash is the default shell in most of the Linux distributions, bash scripting is very efficient as it can simplify certain operations that are hard to accomplish with GUI.
A bash script is a plain text file that includes a single command or series of commands that are read and executed by the bash program. The most crucial part while writing a bash script is to handle errors effectively. When not handled properly, it may leave less of an adverse impact on the system. Exit code is the traditional method of detecting errors in bash script. Thus in this article, we shall discuss various exit codes, and how to read and handle errors using them.
What is a Bash Exit Code?
Exit code is returned by bash for every command executed in the terminal. This code can be used to display error messages when there is any problem while running the script. When a command is executed successfully, bash returns 0 as the exit code, and for any error while executing the command non-zero value is returned which varies from 1 to 255 based on the error type.
Exit code | Description | Examples |
---|
0 | Successful execution | |
---|
1 | Catch generic errors | "Divide by zero", "missing operand", “Permission denied” |
---|
2 | Improper command usage | “Missing keyword”, “No such file or directory” |
---|
| Unable to execute the command | Permission problem |
---|
127 | The issue in path resolution | Command not found |
---|
130 | Fatal error | When interrupted by Ctrl+C |
---|
255 | Out of range | When the exit code exceeds 255 |
---|
Note: The exit code only informs that the script or command is executed fine, but it doesn't tell whether the output from the executed command has got any value or not. For example, listing files in the home directory (doesn't have any files other than hidden files), so simply giving ls will not give any output, but $? gives exit code as 0 which means ls command got executed successfully.
pwd
ls
echo $?
How to Read Exit Codes in Bash
Bash uses a special variable '$?' which holds the exit code of the last command executed either through the terminal or via script. Let us try to execute some commands in the terminal and check their exit code.
Example 1: Exit Code 0
Exit code 0 is returned for commands which ran successfully. For example on running 'pwd' command, $? returns 0.
$ pwd
Example 2: Exit Code 1
mkdir
echo $?
In Linux, certain commands need to be invoked with options. $? returns 1 when mkdir command is invoked without any options as it results in a missing operand error.
echo a=10
echo b=0
echo $((a/b))
echp $?
'$?' returns 1 when any number is divided by zero as it gives the answer “equal to infinity.” No variable can store an infinite amount of data in any programming language. Hence, if any number is divided by zero, we get the arithmetic exception.
cat /etc/sudoers
echo $?
The sudoers file is primarily for system administrators to manage and by default, only the root user has the privilege to edit this file. When any other user (not in the sudoers list) tries to update this file, it would throw a Permission denied error and $? returns 1.
Example 3: Exit Code 2
ls /root/test.sh
echo $?
No such file or directory error is thrown when any user tries to access the file/directory which is not present in the server. Here '/root/test.sh' file doesn't exist, so $? returns 2.
cat /tmp/sleep.t
echo $?
This error occurs when any keyword is missed or misspelled in the script file. In the below example, the 'done' keyword is missed for the while loop, so $? returns 2.
In the below example, the keyword 'then' is misspelled as 'tthen'.
cat /tmp/if.t
echo $?
Example 4: Exit Code 126
ls -lrth /tmp/sleep.t
/tmp/sleep.t
echo $?
Exit code 126 is returned when there is a problem related to permissions. For example, create a script file 'sleep.t' without executing permission set to it. Thus while running the script it would throw permission denied error resulting in a 126 error code.
Example 5: Exit Code 127
hello
echo $?
This error code is returned when the executed command doesn't exist, or when the command isn't in the $PATH environment variable.
This code also appears while attempting to execute a command that is in a different directory. In the below example, the ls command is present in /usr/bin directory. If we run the command from a different directory '/usr/sbin', the 127 code is returned.
which ls
/usr/sbin/ls
echo $?
Example 6: Exit Code 130
cat sleep.sh
sh.sleep.sh
echo $?
This error code is returned when any of the processes or command execution is terminated by pressing 'Ctrl + C'. In the below example, while loop runs infinitely and is terminated by 'Ctrl + C'.
Example 7: Exit Code 255
ip
echo $?
This is a reserved exit status that is easy to reproduce but difficult to interpret. The documentation states that bash receives exit status 255 if an exit code that's out of the range 0-255 is used. However, it can also be reproduced easily in other ways by running certain commands like ip without any options.
Exit Code 255If the code exceeds 256, the exit status returned by bash is the current exit code subtracted by 256. In this example when 'exit 300' is given, the returned exit code is 300-256 = 44.
exit 300
echo $?
Handling Bash Exit Codes in Scripts
Exit code can also be read from the bash script using $?. It can either be assigned to a variable or displayed directly in the echo command. Let's write a sample script list.sh which would list two files and display the exit code based on the file presence.
Script:
#!/usr/bin/sh
ls -a /root/list.sh
echo "The exit code is $?"
ls -a /root/test.sh
echo "The exit code is $?"
Command:
sh list.sh
In this example, '/root/list.sh' file is present hence 0 exit code is returned. But '/root/test.sh' file is not present, so 2 exit code is returned.
Use the Exit code to do a task
Let's create a script named user.sh which will take a username as input. The script will check if the entered user is valid or invalid based on the exit code returned by "cat /etc/passwd | grep $username". For valid users, exit code 0 is returned and for invalid users, exit code 1 is returned.
Script:
#!/usr/bin/sh
echo "Enter a username"
read username
entry=$(cat /etc/passwd | grep $username)
user_exist=$?
if [ $user_exist -eq 0 ]
then
echo "Valid user"
su $username
else
echo "Invalid user"
fi
Command:
sh user.sh
1. Valid user
For a valid user named 'test_user', the terminal prompt got changed from 'root' to 'test_user'.
2. Invalid User
If the user is not present, then an "Invalid User" error message is thrown.
The ‘&&’ logical operator is used for a successful exit code and ‘||’ logical operator is used for an unsuccessful exit code. Let's test valid and invalid user scenarios using logical operators. The following command allows test_user to log in as it is a valid user.
cat /etc/passwd | grep test_user && su test_user || echo "invalid user"
The following command prints "invalid user" as the jack is not present in the server.
cat /etc/passwd | grep jack && su jack || echo "invalid user"
Conclusion
Thus we have learned about various exit codes, how to read them from a terminal or script and how to use them with logical operators. By understanding and utilizing bash exit codes effectively, you can write reliable, robust, and error-proof scripts that simplify your system administration tasks. Thus, Exit codes are a fundamental aspect of bash scripting, providing essential feedback for error handling and debugging.
Similar Reads
Shell Script to List Files that have Read, Write and Execute Permissions
In this article, We will learn how to list all files in the current directory that have Red, Write and Execute permission. Suppose, we have the following files in our current directory : Here, We have a total of 8 files in our current directory. Out of 8, we have Read, Write and Execute permission o
3 min read
How to check if a directory or a file exists in system or not using Shell Scripting?
Shell scripting is really a powerful and dynamic way to automate your tasks. To test if a directory or file already exists in the system or not we can use shell scripting for the same along with test command. To proceed with the test script lets first check the test manual. To open a manual use the
2 min read
Shell Script to Find How Many Terminals Has User Logged-In
Here we are going to see Find How Many Terminals Has User Logged In. Using who command to fetch the user list and then using grep command we can find the number of Terminal that the user has logged in the Linux. We can use LOGNAME or UID to identify the user. UID is a unique User ID assigned to ever
2 min read
Shell Script to Convert a File Content to Lower Case or Upper Case
Here we are going to see how to convert a file to lower case or upper case as specified by the user. We are going to write a POSIX compatible shell script which is going to give us the desired output after input of files such as sample.txt, a text file with a combination of lowercase, uppercase, dig
2 min read
How to Code Your Own Port Scanner Using BASH Script and netcat Tool in Linux?
The first step of penetration testing is reconnaissance (information gathering) which involves scanning for open ports in the machine. There are various tools available on the internet to perform port scanning but, the ability to make your own port scanner is just felt amazing. So here are the steps
3 min read
How To Pass and Parse Linux Bash Script Arguments and Parameters
Parsing and Passing of Arguments into bash scripts/ shell scripts is quite similar to the way in which we pass arguments to the functions inside Bash scripts. We'll see the actual process of passing on the arguments to a script and also look at the way to access those arguments inside the script. Pa
7 min read
Shell Script to Demonstrate Special Parameters With Example
Here, we are going to see what are the special Parameters of the shell script. Before that first, let's understand what is parameters in the shell. The parameter is the entity that stores the value. The variables are the parameters that are defined by the user to use in that specific shell script. A
5 min read
Menu Driven Shell Script to Check Memory and Disk Usages
In Linux most of the time, we automate things using the bash scripts. Some script has only one functionality, but some script can do more than one functions. For that, we have to provide the menu to select the option which function should be performed now. This script is called as Menu-Driven Progra
4 min read
How to prompt for Yes/No/Cancel input in a Linux shell script
You may have noticed that shell programs occasionally ask the user for confirmation by prompting [Y/n] or [Yes/No]. Knowing whether a user wishes to continue with the following stages or not is useful. A similar feature can be added to your script as well. This article will assist you with examples
3 min read
How to Check the Syntax of a Bash Script Without Running It?
A bash script is a text file that contains a sequence of commands that are executed by the bash shell, a Unix-based command-line interface. Bash scripts are used to automate tasks, create utility scripts, and perform a wide range of other functions in the command-line environment. They can include v
5 min read