How to use Linux exit command?

0/5 No votes

Report this app

Description

The exit command is used to exit from the current shell in a Linux or Unix system. Probably you may have used it before if you ever worked with a Linux or Unix terminal.

You can use the exit command with or without parameters if no parameters are provided it will return the status of the last command. This command terminates all the processes normally.

In this article, I will discuss how to use the exit command on Linux operating system.

Syntax of the exit command in Linux

The syntax of using the exit command in Linux is given below –

exit N

Where N is an integer, the exit command will return N if provided in parameters. You can also execute this command without passing the value of N.

Usage of exit command

The exit command can be used in scripts i.e. the status returned by this command can be used as the input to some other command or function to perform some action.

Generally, the return status 0 means the program is executed successfully, and return status 1 indicates some minor errors.

The following are some examples of using exit commands in a Linux system.

Example 1:

The following example shows the usage of the exit command without a parameter.

exit

When you press enter after typing this command in your terminal, all the processes associated with your terminal will get terminated and your terminal window will be closed.

Example 2:

The following example shows the use of exit command with parameter.

exit 5

Now this command will close the terminal and return status of 5. The exit command with parameter is useful in scripts as the returns status can be used as input to some other command to do certain tasks.

If you want you can check the retured status of last executed command by using –

echo $?

Example 3 :

The following example show this use of exit command in a bash script called test.sh –

#!/bin/bash

if [[ "$(whoami)" != root ]]; then
  echo "Only user root can run this script."
  exit 1
fi

echo "The script is executed"

exit 0

The above script will only be executed when run by the root user otherwise you will see a message that only user root can run this script.

You can try this by using the given command –

bash test.sh

execute script

Now if you run it as root by using –

sudo bash test.sh

OR use –

sudo su
bash test.sh

bash exit

If you run this script as root the exit code will be 0 otherwise it will be 1.

You can check manual page of this command by using –

man exit

Conclusion

Ok so we hope now you have got the basic understanding of how to use exit command in Linux. Now if you have a query then write us in the comments below.

Leave a Reply

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