Shell – Linux shell script: Run a program only if it exists, ignore it if it does not exist

executablescriptingshell

I am programming a Linux shell script that will print status banners during its execution only if the proper tool, say figlet, is installed (this is: reachable on system path).

Example:

#!/usr/bin/env bash
echo "foo"
figlet "Starting"
echo "moo"
figlet "Working"
echo "foo moo"
figlet "Finished"

I would like for my script to work without errors even when figlet is not installed.

What could be a practical method?

Best Answer

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
Related Question