Emacs, scripting and anything text oriented.

Check If a Command/Executable Exists from Shell Script

Kaushal Modi

Shell script snippets to check if you have an executable or binary installed in PATH.

Table of Contents

I often need to check if a particular executable is present in the PATH before I can proceed with what I am doing in a shell script. Also, I need to work with both tcsh and bash scripts. Below presents the solution that has worked for these shell scripts for me.

Bash Shell #

The below solution using hash was with the help of this SO solution.

if ! hash some_exec 2>/dev/null
then
    echo "'some_exec' was not found in PATH"
fi

Here is the tl;dr from the above SO solution:

Where bash is your shell/hashbang, consistently use hash (for commands) or type (to consider built-ins & keywords). When writing a POSIX script, use command -v.

Tcsh Shell #

As it turns out, the tcsh shell does not have the same hash command as the bash shell.

But the below solution using where which I found with the help of this SO solution works fine.

if ( `where some_exec` == "" ) then
    echo "'some_exec' was not found in PATH"
endif