Intro To 'exit' Command In Linux
2024-08-06 - By Robert Elder
Use 'exit' To Exit
I use the 'exit' command to exit from the current shell:
exit
![Using Exit Command](https://blog.robertelder.org/intro-to-exit-command/using-exit-command_600x600_qn_s126600.png)
The 'exit' Command As A Shell Builtin
The 'exit' command is typically implemented as a built-in shell command that terminates the current shell process:
type -a exit
exit is a shell builtin
exit --help
exit: exit [n]
Exit the shell.
Exits the shell with a status of N. If N is omitted, the exit status
is that of the last command executed.
Providing A Return Code To 'exit'
You can provide an optional return code to the exit command, to indicate success or failure in a sub-shell (as in this script 'extinguish-fire.sh'):
#!/bin/bash
FIRE_DIRECTORY="${1}"
if [ -d "${FIRE_DIRECTORY}" ]; then
rmdir "${FIRE_DIRECTORY}"
echo "Successfully extinguished the fire in '${FIRE_DIRECTORY}'!"
exit 0;
else
echo "Failed to extinguish fire in '${FIRE_DIRECTORY}': Fire not found."
exit 1;
fi
mkdir apartment-1234
./extinguish-fire.sh apartment-1234
echo $?
0
./extinguish-fire.sh apartment-1234
echo $?
1
Return Codes
By providing a return code to the 'exit' command, you can check the return code of a shell script and handle errors appropriately:
sh -c 'exit 0'
if [ $? -eq 0 ]; then
echo "Success! The shell script ran successfully!"
else
echo "The script failed... Try re-running it I guess?"
fi
Success! The shell script ran successfully!
sh -c 'exit 1'
if [ $? -eq 0 ]; then
echo "Success! The shell script ran successfully!"
else
echo "The script failed... Try re-running it I guess?"
fi
The script failed... Try re-running it I guess?
Using 'exit' To Close The Terminal Window
In a graphical environment, exiting from the top-level shell process will also close the terminal window:
# Opening GNU screen first to increase the shell level:
screen
# Check current shell level:
echo $SHLVL
2
# Exit from screen:
exit
# Check current shell level again:
echo $SHLVL
1
exit # Exit command will now close the terminal window
And that's why the 'exit' command is my favourite Linux command.
![]() A Surprisingly Common Mistake Involving Wildcards & The Find Command
Published 2020-01-21 |
![]() $1.00 CAD |
![]() A Guide to Recording 660FPS Video On A $6 Raspberry Pi Camera
Published 2019-08-01 |
![]() The Most Confusing Grep Mistakes I've Ever Made
Published 2020-11-02 |
![]() Use The 'tail' Command To Monitor Everything
Published 2021-04-08 |
![]() An Overview of How to Do Everything with Raspberry Pi Cameras
Published 2019-05-28 |
![]() An Introduction To Data Science On The Linux Command Line
Published 2019-10-16 |
![]() Using A Piece Of Paper As A Display Terminal - ed Vs. vim
Published 2020-10-05 |
Join My Mailing List Privacy Policy |
Why Bother Subscribing?
|