+++ title = "Check If a Command/Executable Exists from Shell Script" author = ["Kaushal Modi"] description = """ Shell script snippets to check if you have an executable or binary installed in `PATH`. """ date = 2016-11-23T17:07:26-05:00 tags = ["bash", "tcsh", "executable", "exists", "binary"] categories = ["unix", "shell"] draft = false creator = "Emacs 28.1.50 (Org mode 9.5.4 + ox-hugo)" +++
Table of Contents
- [Bash Shell](#bash-shell) - [Tcsh Shell](#tcsh-shell)
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 {#bash-shell} The below solution using `hash` was with the help of [this SO solution](https://stackoverflow.com/a/677212/1219634). ```sh 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 {#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](https://stackoverflow.com/a/22058620/1219634) works fine. ```tcsh if ( `where some_exec` == "" ) then echo "'some_exec' was not found in PATH" endif ``` [//]: # "Exported with love from a post written in Org mode" [//]: # "- https://github.com/kaushalmodi/ox-hugo"