Bash: exit code & if/else conditional

Natarajan Santhosh
2 min readJul 26, 2023

--

How does exit code and if/else conditional work?

The example below checks if rosetta is enabled for docker on apple silicon m1/m2.

From man grep e.g. https://man7.org/linux/man-pages/man1/grep.1.html#EXIT_STATUS

EXIT STATUS
The grep utility exits with one of the following values:

0 One or more lines were selected.

1 No lines were selected.

>1 An error occurred.

To find the exit code of a command

 # when rosetta is disabled, the return code 1 (error)
$ ps -eo args | grep -q "[c]om.docker.virtualization.*rosetta"
$ echo $?
1
# when rosetta is enabled, the return code 0 (success)
$ ps -eo args | grep -q "[c]om.docker.virtualization.*rosetta"
$ echo $?
0

If/Else condition based on return code

if command ; then
# Code to run if the command's exit code is 0 (success).
else
# Code to run if the command's exit code is non-zero (error).
fi

Exit code vs Boolean

In Bash, both using exit codes and using boolean expressions are valid and commonly used practices, depending on the situation and context.

1. Exit Codes:
In Bash, commands generally return an exit code of 0 upon successful execution and a non-zero exit code to indicate an error or failure.

  • Using exit codes in if statements allows you to handle different conditions and outcomes based on the success or failure of a command.
  • This approach is especially useful when dealing with external commands or scripts that follow the standard exit code convention.
  • Exit codes are more expressive and offer greater flexibility in handling various scenarios.
  • Example:
if grep -q "pattern" file.txt ; then
echo "Pattern found in the file."
else
echo "Pattern not found in the file or an error occurred."
fi

2. Boolean Expressions:
Bash supports boolean expressions using the `&&` (logical AND) and `||` (logical OR) operators.

  • This approach is more suitable for combining multiple commands and executing them conditionally based on the success of each command.
  • It can be useful for simple, sequential checks and can make the code more compact.
  • Example:
command1 && command2 && echo "All commands succeeded." || echo "One or more commands failed."

Both approaches have their advantages, and the choice between them depends on the complexity and requirements of your script. If you need to check the success or failure of specific commands and handle different outcomes accordingly, using exit codes with if statements is often a better choice. On the other hand, if you have a series of commands to execute, and you want to proceed or handle errors based on the combined result, boolean expressions might be more appropriate.

Ultimately, the “best practice” is to use the approach that makes your script more readable, maintainable, and suited to the specific task at hand.

--

--

No responses yet