Linux shell script: Run a program only if it exists, ignore it if it does not exist
My interpretation would use a wrapper function named the same as the tool; in that function, execute the real tool if it exists:
figlet() {
command -v figlet >/dev/null && command figlet "$@"
}
Then you can have figlet arg1 arg2...
unchanged in your script.
@Olorin came up with a simpler method: define a wrapper function only if we need to (if the tool doesn't exist):
if ! command -v figlet > /dev/null; then figlet() { :; }; fi
If you'd like the arguments to figlet
to be printed even if figlet isn't installed, adjust Olorin's suggestion as follows:
if ! command -v figlet > /dev/null; then figlet() { printf '%s\n' "$*"; }; fi
You can test to see if figlet
exists
if type figlet >/dev/null 2>&1
then
echo Figlet is installed
fi
A common way to do this is with test -x
aka [ -x
. Here is an example taken from /etc/init.d/ntp
on a Linux system:
if [ -x /usr/bin/lockfile-create ]; then
lockfile-create $LOCKFILE
lockfile-touch $LOCKFILE &
LOCKTOUCHPID="$!"
fi
This variant relies on knowing the full path of the executable. In /bin/lesspipe
I found an example which works around that by combining -x
and the which
command:
if [ -x "`which bunzip`" ]; then bunzip -c "$1"
else echo "No bunzip available"; fi ;;
That way this will work without knowing in advance where in the PATH
the bunzip
executable is.