Skip to content

Instantly share code, notes, and snippets.

@dishbreak
Last active January 19, 2024 08:36
Show Gist options
  • Save dishbreak/27c887799ddd4235406c9c5867d29ff3 to your computer and use it in GitHub Desktop.
Save dishbreak/27c887799ddd4235406c9c5867d29ff3 to your computer and use it in GitHub Desktop.
Easy way in Bash to check that a binary is installed.
#!/bin/bash
# Exit on the first command that returns a nonzero code.
set -e
# Function that checks if a given executable is on the path. If it isn't, prints an install message and exits.
# Usage: check_binary EXECUTABLE_NAME INSTALL_MESSAGE
check_binary() {
if ! which "$1" > /dev/null; then
# Using a subshell to redirect output to stderr. It's cleaner this way and will play nice with other redirects.
# https://stackoverflow.com/a/23550347/225905
( >&2 echo "$2" )
# Exit with a nonzero code so that the caller knows the script failed.
exit 1
fi
}
check_binary "jq" "$(cat <<EOF
You will need jq to run this script.
Install it using your package manager. E.g. for homebrew:
brew install jq
EOF
)"
# a dumb command that uses jq in order to provide a SSCCE snippet
# http://sscce.org/
jq -r ".message" <<EOF
{"message": "hello from jq!"}
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment