Filters
How to search
  • Plain words find names, texts and examples.
  • "two words" finds the exact phrase.
  • --name or -x finds an option.
  • #word looks only inside commands.
  • @grep finds lessons and labs that use grep.
  • Filters: cat:network · in:labs · in:notes · level:rhcsa · ch:8 · root:yes. Put ! before a word to leave it out. OR between words means one of them.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search

exit

End the shell or script with an exit status (0 = success, 1–255 = error); return does the same for a function.

Level
Everyday Linux
Group
Shell and help
Needs root
No
Package
bash (built-in)
Also called
return

What it does

Every command returns an exit status: 0 means success, any other number an error. $? holds the status of the last command. Scripts should end with exit 0 on success and a non-zero code for errors, so that other scripts, cron and systemd know what happened. exit in an interactive shell logs you out.

How to write it

exit [N]
return [N]

Main parts

0
Success.
1
General error.
2
Wrong use (often from builtins).
126
Found, but cannot run.
127
Command not found.
128+N
Killed by signal N (130 = Ctrl+C, 137 = kill -9).

Options 1

Most used

N
The exit status (0–255; default: the status of the last command).

Examples 10

$ run as a normal user# run as root (or with sudo)

  1. 1End a script with success

    tail -1 backup.sh
    exit 0

    The caller sees 0.

  2. 2Exit with an error

    [ -d /backup ] || { echo "no backup folder" >&2; exit 1; }

    Message to stderr, code 1.

  3. 3See the status of the last command

    ls /nothing; echo $?
    ls: cannot access '/nothing': No such file or directory
    2

    ls uses 2 for this error.

  4. 4Command not found

    nosuchcommand; echo $?
    127

    127 = not found.

  5. 5Killed by Ctrl+C

    sleep 100
    ^C
    echo $?
    130

    128 + 2 (SIGINT).

  6. 6Return from a function

    isroot() { [ "$(id -u)" -eq 0 ] && return 0 || return 1; }; isroot && echo root || echo "not root"

    return = exit for functions.

  7. 7Use the status in if

    if grep -q lisa /etc/passwd; then echo found; fi

    if checks the exit status.

  8. 8Pass on the status of the last command

    cp a b; exit

    exit without N uses the status of cp.

  9. 9Leave a root shell

    exit

    Back to your own user.

  10. 10Exit codes in systemd

    systemctl status myapp | grep -i 'code='

    status=203/EXEC = the program could not be run.

Exit codes

N :: The given value (or the last command's status).