Exit codes

We have already seen that when a program encounters issues it exits, usually with an error message. What does exits means? Simply that the code execution terminates and the program, or the script, returns an exit code that informs the system of what happened. This is very handy for us, since we can trap the exit code of a program and decide what to do based on its value.

0

Success

1

Failure

2

Misuse of builtin

126

Command not executable

127

Command not found

128

Invalid argument

128+x

Fatal error exit with signal x

130

Execution terminated by Ctrl +C

255

Exit state out of boundary (0-255)

 

So, maybe you already guessed, each execution terminates with an exit code, whether successful or not, with an error message or silently:

zarrelli:~$ date ; echo $?
Thu 2 Feb 19:17:48 GMT 2017
0

As you can see, the exit code is 0 because the command was executed without issues. Now, let's try this:

zarrelli:~$ asrw ; echo $?
bash: asrw: command not found
127

It is a command not found as we just typed a meaningless bunch of characters. Now a while cycle will not terminate until we press Ctrl + C.

while true ; do echo 1 ; done  

You will see your screen filling up with a column of infinite 1. Press Ctrl + C and you will see:

^C  

Now, let's check the exit code:

zarrelli:~$ echo $?
130

Now, let's create a never-ending script:

#!/bin/bash    
while true; do
echo ${$}
done

Although true is a never-ending cycle, since the condition is always true, it will print to the stdout the PID of the shell, which the script is running in. Let's open a second terminal and launch the script from the first; you will see the same PID repeated indefinitely:

1764
1764
1764
1764
1764

Now, from the second terminal, using the same user or root user, issue:

zarrelli:~$ kill -9 1764  

Go back to the first terminal, and you see your script terminated:

1764
1764
1764
1764
Killed

Time to check the exit status of the script:

zarrelli:~$ echo $?
137

Which is 128 + 9, 9 being the signal we used to kill the process. Let's run the script again:

1778
1778
1778
1778

Now kill it from the second terminal with:

zarrelli:~$ kill -15 1778    
1778
1778
1778
1778
Terminated

Back to the first terminal to check the exit code of the script:

zarrelli:~$ echo $?
143

And 143 is exactly 128 + 15, as we expected.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.255.127