1

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?

Zombo
  • 1
  • 55
  • 342
  • 375
David Lam
  • 4,339
  • 2
  • 22
  • 33

3 Answers3

1

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 ifs:

type fortune &> /dev/null && type cowsay &> /dev/null && (fortune | cowsay -W 65)
Mihai Maruseac
  • 20,182
  • 7
  • 55
  • 109
1

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

Check if a program exists from a Bash script

Community
  • 1
  • 1
Zombo
  • 1
  • 55
  • 342
  • 375
0

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
Guru
  • 15,464
  • 2
  • 31
  • 43