How to check if a program exists from a Bash/Shell script

0 min read 123 words

You can look to use:

command -v <the_command>

There are also 2 other ways, that we will run through a little further down, but for now..

How to use the command if a conditional

if ! command -v <the_command> &> /dev/null
then
    echo "<the_command> could not be found"
    exit
fi

To summarize, there are 3 ways you can do this

Option 1 - Using command

command -v foo >/dev/null 2>&1 || { echo >&2 "foo is not installed. Aborting."; exit 1; }

Option 2 - Using type

type foo >/dev/null 2>&1 || { echo >&2 "foo is not installed. Aborting."; exit 1; }

Option 3 - Using hash

hash foo 2>/dev/null || { echo >&2 "foo is not installed. Aborting."; exit 1; }
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags