We can define a function for checking whether as executable exists by using which
:
function is_executable() {
which "$@" &> /dev/null
}
The function is called just like you would call an executable. "$@"
ensures that which
gets exactly the same arguments as are given to the function.
&> /dev/null
ensures that whatever is written to stdout or stderr by which
is redirected to the null device (which is a special device which discards the information written to it) and not written to stdout or stderr by the function.
Since the function doesn't explicitly return with an return code, when it does return, the exit code of the latest executed executable—which in this case is which
—will be the return code of the function. which
will exit with a code that indicates success if it is able to find the executable specified by the argument to the function, otherwise with an exit code that indicates failure. This behavior will automatically be replicated by is_executable
.
We can then use that function to conditionally do something:
if is_executable name_of_executable; then
echo "name_of_executable was found"
else
echo "name_of_executable was NOT found"
fi
Here, if executes the command(s) written between it and then
—which in our case is is_executable name_of_executable
—and chooses the branch to execute based on the return code of the command(s).
Alternatively, we can skip defining the function and use which
directly in the if
-statement:
if which name_of_executable &> /dev/null; then
echo "name_of_executable was found"
else
echo "name_of_executable was NOT found"
fi
However, I think this makes the code slightly less readable.