by Sai gowtham

How to Check if the program exists from a Bash script

You can use the posix compatible command to check, if the command exists from a bash script or not.

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

if it returns >0 when the command is not found or an error occurs.

similary you can use type and hash.

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

The below example will show you gdate if exists else it shows date.

if hash gdate 2>/dev/null; then
        gdate "$@"
    else
        date "$@"
fi

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course