I have the following in my .bashrc to print a funny looking message:
fortune | cowsay -W 65
I don't want this line to run if the computer doesn't have fortune
or cowsay
installed.
What's the best or simplest way to perform this check?
You can use type
or which
or hash
to test if a command exists.
From all of them, which
works only with executables, we'll skip it.
Try something on the line of
if type fortune &> /dev/null; then
if type cowsay &> /dev/null; then
fortune | cowsay -W 65
fi
fi
Or, without if
s:
type fortune &> /dev/null && type cowsay &> /dev/null && (fortune | cowsay -W 65)
type
is the tool for this. It is a Bash builtin. It is not obsolete as I once thought, that is typeset
. You can check both with one command
if type fortune cowsay
then
fortune | cowsay -W 65
fi
Also it splits output between STDOUT and STDERR, so you can suppress success messages
type fortune cowsay >/dev/null
# or failure messages
type fortune cowsay 2>/dev/null
# or both
type fortune cowsay &>/dev/null
If your intention is not to get the error messages appear in case of not being installed, you can make it like this:
(fortune | cowsay -W 65) 2>/dev/null