1

I understand that EXIT command causes the shell or program to terminate. But what is the difference between the below:

exit 2
exit 3
exit 4
exit $?

how is exit 2 different from exit 3 and so on

Rahul sawant
  • 375
  • 3
  • 5
  • 13

3 Answers3

3

This is only an exit code. 0 is for fine exit, otherwise it's the error code. $? is a shell variable storing the previous exit value (so the program which ran before your one).

bagage
  • 1,034
  • 1
  • 19
  • 43
  • More precisely, it's a shell variable or shell parameter. It's not an environment variable. – Barmar Feb 18 '14 at 16:45
  • `bash` distinguishes shell variables as a parameter denoted by a name. This excludes the positional parameters (denoted by non-zero numbers) and the special parameters (denoted by various punctuation marks, symbols and 0). – chepner Feb 18 '14 at 17:36
2

The exit command takes a single value which is the value of the process (e.g. shell) return code. $? is the return code from the last command executed by the shell.

For instance, the script which exits with a return code corresponding to the first argument:

#!/bin/sh
exit $1

Would give you:

# ./script 1
# echo $?
1
# ./script 2
# echo $?
2

Note on most UNIX systems, the return code is limited to a numeric value between 0 and 255, with 0 indicates success and 1-255 providing error information (specific to each process).

isedev
  • 16,514
  • 3
  • 51
  • 58
1

From the Advanced Bash-Scripting Guide, Chapter 6: Exit and Exit Status:

The exit command terminates a script, just as in a C program. It can also return a value, which is available to the script's parent process.

So the exit command lets you assign your own exit value, which you could describe in its man page, for example.

The $? will return the exit code of the previous command. For example; You write a script that executes cat example.txt, which results exit code 1. If you then do exit $?, your script will exit with the same code as cat example.txt

Community
  • 1
  • 1
Bas Peeters
  • 3,085
  • 4
  • 30
  • 47