exit - Linux


The exit command in Linux is used to terminate a shell session, script, or command execution environment. This can be useful to manually close terminal sessions or to neatly end a script’s execution based on conditions or successful completion. Determining the exit status can also communicate success or the nature of an error to other scripts or logging systems.


exit [n]

Where n is an optional integer parameter indicating the exit status to be returned by the shell process upon termination. If n is not provided, exit uses the status of the last command executed.


The exit command itself does not support many options or flags. Its main parameter is the optional exit status:

  • [n]: An integer value to represent the exit status. Must be between 0 and 255. Here:
    • 0 indicates success.
    • Non-zero values can be used to describe specific error types or scenarios.


  1. Simple Exit:
    Exit a shell script successfully:

    exit 0
  2. Conditional Exit:
    Exit with an error code if a file is not found:

    if [ ! -f myfile.txt ]; then
      echo "File not found!"
      exit 1
  3. Using Exit Status:
    Using the exit status of a command to determine script termination:

    grep "username" /etc/passwd
    if [ $? -ne 0 ]; then
      exit 2

Common Issues

  • Invalid Exit Codes: Specifying an exit code outside of the 0-255 range may return unexpected results as exit codes are 8-bit integers.

  • Avoid confusion between shell exit status and command outputs.


exit can be effectively used in shell scripts combined with other commands. For example, in backup scripts to stop execution if mounting a drive fails:

mount /dev/sdb1 /mnt/backup || exit 1
tar czf /mnt/backup/mybackup.tar.gz /home/user || exit 2
umount /mnt/backup
exit 0
  • logout: Similar to exit, used to end a login shell session.
  • return: Exits a shell function with an optional return value, useful within a script.
  • bash, sh, zsh: Different shell environments where exit can be used.

For further exploration of shell scripting and command line usage, the official documentation and extensive community resources like forums and tutorials can provide deeper insights.