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?

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.