Emacs, scripting and anything text oriented.

Check If a Command Exists from Shell Script

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 different solutions that have 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
    echo "'some_exec' was not found in PATH"

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

Looks like 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"


comments powered by Remarkbox