Ubuntu – the meaning of exit 0, exit 1, and exit 2 in a bash script


I'm doing some practice exercises.

Write a script that will be given a month number as the argument and will translate this number into a month name. The result will be printed to stdout.

I made a solution:

# Test for number of argument

if [ "$#" -eq 0 ] ; 
  echo -e "No argument."
  echo -e "Write a number between 1 and 12."
  exit 1
elif [ "$#" -gt 1 ] ;
  echo -e "More than 1 argument."
  echo -e "Write a number between 1 and 12."
  exit 1
  case "$numb" in
    1) echo "Month: January";;
    2) echo "Month: February";;
    3) echo "Month: March";;
    4) echo "Month: April";;
    5) echo "Month: May";;
    6) echo "Month: June";;
    7) echo "Month: July";;
    8) echo "Month: August";;
    9) echo "Month: September";;
   10) echo "Month: October";;
   11) echo "Month: November";;
   12) echo "Month: December";;
    *) echo -e "You wrote a wrong number. Try again with writing number between 1 and 12.";;
exit 2
exit 0

What do exit 1, exit 0 and exit 2 mean, and why do we use them?

Best Answer

Here's one good reference for shell exit codes:

Exit code 0        Success
Exit code 1        General errors, Miscellaneous errors, such as "divide by zero" and other impermissible operations
Exit code 2        Misuse of shell builtins (according to Bash documentation)        Example: empty_function() {}

Caveat: Using the proper exit code is not a requirement and is not enforced by the shell. Developers can ignore the guidance if they think it wise.