mles mles - 7 months ago 16
Bash Question

How to check if command -v $1 >/dev/null 2>&1; is false?

I'm looking for a proper way to check if a command does not exist. I've read through Check if a program exists from a Bash script. So far I came up with:

command_exists () {
command -v $1 >/dev/null 2>&1;
}

if command_exists aws; then
echo # null
else
brew install awscli
fi


There has to be a way to only have one if clause like:

if ! command_exists aws; then
brew install awscli
fi


update: nevermind, above solution works.

Answer

I have a similar function defined and there’s no reason why your snippet of shell code shouldn’t work.

if ! command_exists aws; then
    brew install awscli
fi

If you prefer, you can shorten this like so:

command_exists aws || brew install awscli