First, the idiomatic way to check if a command worked is directly in the if
statement.
if command; then
echo notify user OK >&2
else
echo notify user FAIL >&2
return -1
fi
(Good practice: Use of >&2
to send the messages to stderr.)
There are several ways you could simplify this.
Write a function
Just like in other programming languages, common logic can be moved into shared functions.
check() {
local command=("$@")
if "${command[@]}"; then
echo notify user OK >&2
else
echo notify user FAIL >&2
exit 1
fi
}
check command1
check command2
check command3
Don't print anything
In idiomatic shell scripts, successful commands don't print anything. Printing nothing means success in UNIX. Also, any well-behaved command that fails will already print an error message, so you don't need to add one.
Taking advantage of those two facts, you could use || exit
to exit whenever a command fails. You can read ||
as "or else".
command1 || exit
command2 || exit
command3 || exit
Use -e
Alternatively, you could enable the -e
shell flag to have the shell exit whenever a command fails. Then you don't need anything at all.
#!/bin/bash -e
command1
command2
command3
Don't print anything
If you do in fact want error messages, but are okay with no success messages, a die()
function is popular.
die() {
local message=$1
echo "$message" >&2
exit 1
}
command1 || die 'command1 failed'
command2 || die 'command2 failed'
command3 || die 'command3 failed'