Skip to content

Linux Foundations / Find your way around Linux ยท Step 30 of 63

Lesson: exitSwitch
โ† Linux Foundations

Shell and files

exit

End a shell session with exit and understand exit status codes.

exit ends the current shell. It is built into the shell itself.

Leaving a shell

$ exit

What happens next depends on how the shell was started. In a terminal window, the window or tab often closes. Over SSH, you are logged out of the remote machine and return to your own. If you started a shell inside another shell, you go back to the outer one:

$ bash
$ exit
exit
$

Pressing Ctrl+D on an empty line usually does the same. Some setups ignore it, and some terminals keep the window open.

Exit status

Every command finishes with a number called its exit status. By convention 0 means success and any other value means some kind of failure. The special variable $? holds the status of the last command:

$ ls /etc/hostname
/etc/hostname
$ echo $?
0
$ ls /nothere
ls: cannot access '/nothere': No such file or directory
$ echo $?
2

The meaning of non-zero values depends on the program, so check its manual. $? changes after every command, including echo.

Choosing a status

Give exit a number from 0 to 255:

$ bash
$ exit 3
exit
$ echo $?
3

With no number, exit uses the status of the last command that ran. Scripts use this to report whether they worked:

#!/bin/bash
[ -f config.txt ] || exit 1
echo "config found"

If a script says exit, it ends the shell running the script. But if you source such a file, it runs in your current shell, so exit closes your session.

Before you leave

Background jobs may be affected when a session ends. If you have stopped jobs, bash warns you once instead of exiting straight away. Run jobs to see them.

Try it

  1. Start bash inside your terminal and leave it with exit.
  2. Run true, then echo $?.
  3. Run false, then echo $?.
  4. Start another bash, run exit 7 and check the status.

Check your understanding

exit

All 4 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.