More Bash answers

by Danny
Published 2 min read

Every command returns an exit status, where 0 means success. Learn to check it with if, && and ||, when $? is useful, and the traps with pipes and local variables.

The short answer

#

Put the command straight after if. Bash runs it and takes the first branch when it exits with status 0, which means success.


_10
if cp config.example.json config.json; then
_10
echo "Copied"
_10
else
_10
echo "Copy failed" >&2
_10
exit 1
_10
fi

For one-liners, use && to run something only on success and || to run something only on failure.


_10
mkdir -p build && echo "Build folder ready"
_10
cd build || exit 1

Why it happens

#

Every command in Unix finishes with an exit status, a number from 0 to 255. Zero means it worked. Any other value means something went wrong, and the program decides what each number means. For example, grep returns 0 when it finds a match, 1 when it finds none and 2 when there is an error such as a missing file.

Bash keeps the status of the most recent command in the special variable $?. if, while, && and || all read that status for you, so you rarely need to look at $? directly. This is also why if in Bash does not need brackets: [[ ... ]] is just one more command that returns 0 or 1.

How to fix it

#

Test the command with if

This is the clearest form and the one to reach for first.


_10
if grep -q "^DATABASE_URL=" .env; then
_10
echo "Database configured"
_10
fi
_10
_10
# Negate with !
_10
if ! command -v docker > /dev/null; then
_10
echo "Docker is not installed" >&2
_10
exit 1
_10
fi

You can capture output and check the status at the same time. The status of an assignment from command substitution is the status of the command.


_10
if version=$(node --version 2>/dev/null); then
_10
echo "Node $version"
_10
else
_10
echo "Node not found"
_10
fi

Use && and || for short checks


_10
npm test && npm run build
_10
_10
cd "$project_dir" || { echo "Cannot cd to $project_dir" >&2; exit 1; }

The braces group several commands. Note the spaces inside them and the semicolon before the closing brace; both are required.

Read $? when you need the exact code

$? is useful when different failure codes need different handling. Save it straight away, because the very next command overwrites it.


_10
grep -q "error" app.log
_10
status=$?
_10
_10
case $status in
_10
0) echo "Errors found" ;;
_10
1) echo "No errors" ;;
_10
*) echo "grep failed with status $status" >&2 ;;
_10
esac

Check every command in a pipeline

A pipeline's status is the status of its last command, so a failure earlier in the pipe is hidden.


_10
curl -fsS https://example.com/data.json | jq '.items' > items.json
_10
echo "${PIPESTATUS[@]}" # for example: 22 0

PIPESTATUS holds one status per command in the most recent pipeline. To make the whole pipeline fail when any part fails, turn on set -o pipefail at the top of the script.

Make your own scripts return a useful status

Use exit 0 for success and a non-zero number for failure, and return inside functions. Write error messages to standard error with >&2 so they do not mix with real output.


_10
require_file() {
_10
if [[ ! -f $1 ]]; then
_10
echo "Missing $1" >&2
_10
return 1
_10
fi
_10
}
_10
_10
require_file package.json || exit 1

Common pitfalls

#
  • Testing $? too late. An echo or even a [[ ]] test in between replaces the value. Save it in a variable on the next line.
  • Writing if [ $? -eq 0 ] after the command. It works, but if command; then is shorter and cannot pick up the wrong status.
  • Treating a && b || c as if-else. If b fails, c runs as well. Use a real if when the success branch can fail.
  • local hides the status. In a function, local out=$(cmd) always succeeds, because local itself succeeded. Declare first with local out, then assign with out=$(cmd).
  • Assuming non-zero always means error. Some tools use 1 for a normal "no result", such as grep and diff. Check the man page.
  • Relying on set -e alone. It does not stop the script for commands inside if, while, or on the left of && and ||. Check important commands explicitly.
#

Was this resource helpful?