Session and utilities

The exit command

Ends the shell or the script you are in, returning an exit status.

Syntax

exit [codigo]Try it in the terminal →

Most useful options

n codigoStatus it ends with. 0 means success; any other value means failure.
(sin n)Ends with the status of the last command run, the one $? shows.

Copy-ready examples

$ exitcloses the current session.
$ exit 0closes reporting success.
$ exit 1closes reporting failure, useful for a script that could not finish.
$ (echo hola; exit 3); echo $?exit inside ( ) only closes that subshell, and the shell carries on.

Example output

hola
3
$ bash -c 'exit 3'; echo $?runs a new shell that exits with 3 and shows that code.

Example output

3

You can try them in the browser terminal: it does not touch your computer.

Common errors

MessageCauseFix
bash: exit: abc: numeric argument requiredexit only accepts a number as its status and received text. Bash ends with status 2.Pass a whole number, such as exit 1.
bash: exit: too many argumentsYou passed more than one argument to exit.Leave a single number or no argument: exit 1.

Typical mistakes

  • Inside a function, exit closes the whole shell. To leave only the function, use return.
  • A trap on EXIT runs before the shell terminates, so it is useful for deleting temporary files.
  • An exit inside ( ) does not close your terminal, only that subshell.

Differences from similar commands

  • logout: only leaves a login shell. Outside one it fails; exit works in any shell.
  • return: leaves a function or a file loaded with source, without closing the shell. exit closes the whole shell.

Related commands

FAQ

Is closing the terminal window the same as exit?

Almost. When you close the window the shell receives SIGHUP and ends; exit is the orderly exit, and it also runs the EXIT trap.

Why do scripts end with exit 0?

So the caller knows everything went well. Without exit, the script returns the status of the last command it ran.

Why doesn't exit close the shell when there are stopped jobs?

Bash warns that there are stopped jobs and does not exit. If you type exit again with no command in between, it does exit and ends the stopped jobs.

Learn to actually use it

The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.

Start the free course