exit ends the current shell. It is built into the shell itself.
Leaving a shell
$ exitWhat 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 $?
2The 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 $?
3With 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
- Start
bashinside your terminal and leave it withexit. - Run
true, thenecho $?. - Run
false, thenecho $?. - Start another
bash, runexit 7and 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.