Loading...
Shell Script

Exit Status

Any program completes execution under the UNIX or Linux system, it returns a status back to the system. This status is a number that usually indicates whether the program successfully run and then called as exit status. By convention, an exit status of zero indicates that a program succeeded, and nonzero(1-255) indicates that it failed. Failures can be caused by invalid arguments passed to the program, or by an error condition detected by the program.

The shell variable $? is automatically set by the shell to the exit status of the last command executed. Naturally, echo is used to display its value at the terminal.

$ cp file4 file_old
$ echo $?
0
$ cp filex file_oldx     ## Here we are trying to copy a file which is not existing.
cp: cannot stat `filex':No such file or directory
$ echo $?
1

Note that the numeric result of a “failure” for some commands can vary from one UNIX version to the next, but success is always signified by a zero exit status.

The following are the few exit status which will be generated regularly while executing the scripts or commands.

Exit Code    Description
1                    General Input Error
2                    Misuse of command and very rare
126                Cannot Invoke the requested command. For Example executing a script won’t have                              executable permission.
127                Command not found error.
128+n            Fatal error signal “n” (for example, kill-9=137)
130                Script terminated by Ctrl-C

In shell scripting we can make our scripts generic using the exit codes. We can exit our scrip using exit command followed by a number.

Following examples narrates Exit States:

To exit with exit status 1

#!/bin/bash
exit 1 ## Mention the value to exit with the same status.
###To exit with the value 1.

To exit with exit status 0

#!/bin/bash
echo Webnoid Schools
exit 0      ### To exit with the value 0.

Leave a Reply

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