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
  • 62
  • 391
  • 407
David Lam
  • 4,689
  • 3
  • 23
  • 34

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,967
  • 7
  • 57
  • 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
  • 62
  • 391
  • 407
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
  • 16,456
  • 2
  • 33
  • 46