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.
_10if cp config.example.json config.json; then_10 echo "Copied"_10else_10 echo "Copy failed" >&2_10 exit 1_10fi
For one-liners, use && to run something only on success and || to run something only on failure.
_10mkdir -p build && echo "Build folder ready"_10cd 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.
_10if grep -q "^DATABASE_URL=" .env; then_10 echo "Database configured"_10fi_10_10# Negate with !_10if ! command -v docker > /dev/null; then_10 echo "Docker is not installed" >&2_10 exit 1_10fi
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.
_10if version=$(node --version 2>/dev/null); then_10 echo "Node $version"_10else_10 echo "Node not found"_10fi
Use && and || for short checks
_10npm test && npm run build_10_10cd "$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.
_10grep -q "error" app.log_10status=$?_10_10case $status in_10 0) echo "Errors found" ;;_10 1) echo "No errors" ;;_10 *) echo "grep failed with status $status" >&2 ;;_10esac
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.
_10curl -fsS https://example.com/data.json | jq '.items' > items.json_10echo "${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.
_10require_file() {_10 if [[ ! -f $1 ]]; then_10 echo "Missing $1" >&2_10 return 1_10 fi_10}_10_10require_file package.json || exit 1
Common pitfalls
#- Testing
$?too late. Anechoor 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, butif command; thenis shorter and cannot pick up the wrong status. - Treating
a && b || cas if-else. Ifbfails,cruns as well. Use a realifwhen the success branch can fail. localhides the status. In a function,local out=$(cmd)always succeeds, becauselocalitself succeeded. Declare first withlocal out, then assign without=$(cmd).- Assuming non-zero always means error. Some tools use 1 for a normal "no result", such as
grepanddiff. Check the man page. - Relying on
set -ealone. It does not stop the script for commands insideif,while, or on the left of&&and||. Check important commands explicitly.
Related reading
#Was this resource helpful?