Linux and Networking

Linux and Networking

4.12. What is the exit command and exit status?

We have already seen in previous exercises how to use the exit command to exit a script automatically.

 

Just as we can do with shell scripts, every command, when executed, returns an exit status also called return status or exit status. A command executed successfully, for example, returns a value of 0, while a command that has failed will show a value other than 0 (error code), which is generally a number between 0 and 255. To view the exit status of a command just show the variable $?.

 

Let’s see this with a practical example. This is the result of running several commands in a terminal:

As you can see, the exit status of a command with a normal response is 0 and that of a non-existent command gives a value of 127.

 

Let’s imagine we have the following shell script:

 

#!/bin/bash

echo hello

exit 48

 

If I run it in a terminal I will get the following result:

 

$ ./miniscript.sh

hello

$echo$?

48

 

This is because the script’s exit 48 command forces the script’s exit status to be 48. Generally an exit status other than 0 indicates any type of problem or error. If you use exit status in your scripts, always keep this in mind.

 

Suggested exercises:

1 Create a script that returns a value of 0 if at least one parameter is entered and 1 otherwise.

2 Run a second script to check the exit status of the first script.

 

The Demeter Project