Linux

Linux bash exit status and how to set exit status in bash

Can you explain bash exit status code? How do I set bash exit status in my Linux shell scripts?

Each Linux or Unix command returns a status when it terminates normally or abnormally. You can use value of exit status in the shell script to display an error message or run commands. For example, if tar command is unsuccessful, it returns a code which tells the shell script to send an e-mail to sysadmins.

 

 

More on Linux bash shell exit status codes

  1. Every Linux or Unix command executed by the shell script or user, has an exit status.
  2. The exit status is an integer number.
  3. For the bash shell’s purposes, a command which exits with a zero (0) exit status has succeeded.
  4. A non-zero (1-255) exit status indicates failure.
  5. If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126.
  6. All of the Bash builtins return exit status of zero if they succeed and a non-zero status on failure.

How do I display the exit status of shell command?

You can use special shell variable called $? to get the exit status of the previously executed command. To print $? variable use the echo command/printf command. The syntax is:
command
echo $?

OR
/path/to/script.sh
command
date
echo $?
printf "%dn" $?
## run non-existence command ##
foobar13535
## display status code ##
echo $?

Display bash exit status in Linux

How to store the exit status of the command in a shell variable

Assign $? to a shell variable. The syntax is:

date
status=$?
echo "The date command exit status : ${status}"

Linux exit status and the conditional/list constructs

A simple shell script to locate host name (findhost.sh)

#!/bin/bash
# set var 
FILE="/etc/hosts"
 
# get host name 
read -p "Enter a hostname : " hostname
 
# try to locate hostname/computer name in $FILE
grep -q -w "${hostname}" "${FILE}"
 
# store exit status of grep
# if found grep will return 0 exit status
# if not found, grep will return a nonzero exit status
status=$?
 
if test $status -eq 0
then
	echo "Host '$hostname' found in $FILE file."
else
	echo "Host '$hostname' not found in $FILE file."
fi

How to use the && and || operators with exit codes

The syntax is:

command && echo "success"
command || echo "failed"
command && echo "success" || echo "failed"

If a dir named “/tmp/foo” not found create it:
[ ! -d "/tmp/foo" ] && mkdir -p "/tmp/foo"
For example, show usage syntax when filename not passed as the command line arg:

#!/bin/Bash
_files="[email protected]"
 
## fail safe ##
[[ "$_files" == "" ]] && { echo "Usage: $0 file1.png file2.png"; exit 1; }
 
## continue below ##

Here is another shell script that shows usage:

#!/bin/bash
set -e
I=~/bin/tags.deleted.410
O="/tmp/https.www.cyberciti.biz.410.url.conf"
t="$1"
[ ! -f "$I" ] && { echo "$I file not found."; exit 10; }
[ "$t" == "" ] && { echo "Usage: $0 number-of-urls-to-purge-from-$I"; exit 11; }
 
>$O
 
cat "$I" | sort | uniq | while read -r u
do
	uu="${u##https://www.cyberciti.biz}"
	echo "~^$uu 1;" >>"${O}"
done
echo "* Config file created at ${O} ..."
echo "* Installing ${O} file on utls-wp-mg-www ..."
~/bin/install.py "${O}"
echo "* Send config to rest of cluster nodes ... "
~/bin/install.py --sync --cluster --reload cbz-www
echo "* Building list purge urls for Cloudflare CDN ..."
sleep 1
url=""
while IFS= read -r u
do
        url="$url $u"
done <<<"$(tail -${t} ${I})"
[ "$url" != "" ] && ~/bin/cloudflare.purge.urls.sh "$url"
[ -f "$O" ] && rm -f "$O"

List of common exit codes for GNU/Linux

Exit CodeDescription
0Success
1Operation not permitted
2No such file or directory
3No such process
4Interrupted system call
5Input/output error
6No such device or address
7Argument list too long
8Exec format error
9Bad file descriptor
10No child processes
11Resource temporarily unavailable
12Cannot allocate memory
13Permission denied
14Bad address
15Block device required
16Device or resource busy
17File exists
18Invalid cross-device link
19No such device
20Not a directory
21Is a directory
22Invalid argument
23Too many open files in system
24Too many open files
25Inappropriate ioctl for device
26Text file busy
27File too large
28No space left on device
29Illegal seek
30Read-only file system
31Too many links
32Broken pipe
33Numerical argument out of domain
34Numerical result out of range
35Resource deadlock avoided
36File name too long
37No locks available
38Function not implemented
39Directory not empty
40Too many levels of symbolic links
42No message of desired type
43Identifier removed
44Channel number out of range
45Level 2 not synchronized
46Level 3 halted
47Level 3 reset
48Link number out of range
49Protocol driver not attached
50No CSI structure available
51Level 2 halted
52Invalid exchange
53Invalid request descriptor
54Exchange full
55No anode
56Invalid request code
57Invalid slot
59Bad font file format
60Device not a stream
61No data available
62Timer expired
63Out of streams resources
64Machine is not on the network
65Package not installed
66Object is remote
67Link has been severed
68Advertise error
69Srmount error
70Communication error on send
71Protocol error
72Multihop attempted
73RFS specific error
74Bad message
75Value too large for defined data type
76Name not unique on network
77File descriptor in bad state
78Remote address changed
79Can not access a needed shared library
80Accessing a corrupted shared library
81.lib section in a.out corrupted
82Attempting to link in too many shared libraries
83Cannot exec a shared library directly
84Invalid or incomplete multibyte or wide character
85Interrupted system call should be restarted
86Streams pipe error
87Too many users
88Socket operation on non-socket
89Destination address required
90Message too long
91Protocol wrong type for socket
92Protocol not available
93Protocol not supported
94Socket type not supported
95Operation not supported
96Protocol family not supported
97Address family not supported by protocol
98Address already in use
99Cannot assign requested address
100Network is down
101Network is unreachable
102Network dropped connection on reset
103Software caused connection abort
104Connection reset by peer
105No buffer space available
106Transport endpoint is already connected
107Transport endpoint is not connected
108Cannot send after transport endpoint shutdown
109Too many references
110Connection timed out
111Connection refused
112Host is down
113No route to host
114Operation already in progress
115Operation now in progress
116Stale file handle
117Structure needs cleaning
118Not a XENIX named type file
119No XENIX semaphores available
120Is a named type file
121Remote I/O error
122Disk quota exceeded
123No medium found
125Operation canceled
126Required key not available
127Key has expired
128Key has been revoked
129Key was rejected by service
130Owner died
131State not recoverable
132Operation not possible due to RF-kill
133Memory page has hardware error

The perror command explain error codes which is part of MySQL/MariaDB package:
perror 0
perror 1

Conclusion

This page explained bash exit status and related commands. For more info see bash shell man page here.

Tags
Show More

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Close