←Command Line/Guided Lab Exit Shells and Exit Codes60:00
Click the virtual machine below to start practicing
>_ Tekhnikum | Lab
Setting up virtual machine…
Preparing lab files…
Starting terminal services…
This lab machine has stopped
Your progress through the guide is saved. Start a fresh machine to keep practicing.
Introduction
Every command finishes with an exit status: 0 means success and anything else means failure. Shells end with exit, and you can nest one shell inside another.
This lab is the hands-on companion to the exit lesson from Linux Journey (CC BY-SA 4.0).
Read the Exit Status
$? holds the status of the last command:
ls /etc > /dev/null
echo $?
ls /no/such/place
echo $?
0
2
Exit with a Status
exit N ends a shell with status N. Try it in a throwaway shell:
bash -c 'exit 3'
echo $?
3
Nested Shells
Running bash starts a new shell inside the current one. $SHLVL counts how deep you are:
echo $SHLVL
bash
echo $SHLVL
exit
echo $SHLVL
exit (or Ctrl+D on an empty line) leaves the inner shell and returns you to the first one.
Summary
Every command returns an exit status; 0 is success.