Consider this example function to check if a host is up:
is_alive() {
ping -c1 "$1" &> /dev/null
}
This function sends a single ping to the host specified by the first function parameter.
The output and error output of ping
are both redirected to /dev/null
,
so the function will never output anything.
But the ping
command will have exit code 0 on success,
and non-zero on failure.
As this is the last (and in this example, the only) command of the function,
the exit code of ping
will be reused for the exit code of the function itself.
This fact is very useful in conditional statements.
For example, if host graucho
is up, then connect to it with ssh
:
if is_alive graucho; then
ssh graucho
fi
Another example: repeatedly check until host graucho
is up, and then connect to it with ssh
:
while ! is_alive graucho; do
sleep 5
done
ssh graucho