Skip to main content

Raymii.org Logo (IEC resistor symbol)logo

Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher

Bash Bits: Check if a program is installed

Published: 05-05-2019 | Author: Remy van Elst | Text only version of this article


Table of Contents


Bash Bits are small examples and tips for Bash Scripts. This bash bit shows youhow to check if a piece of software is installed on a machine. It's a functionyou can use in your shell scripts.

If you like this article, consider sponsoring me by trying out a Digital OceanVPS. With this link you'll get $100 credit for 60 days). (referral link)

All Bash Bits can be found using this link

command_exists()

The function uses the command binary to check if a binary is available.command handles all the magic of searching your path, checking if something isexecutable, all the dificult stuff that could also be different on otherdistributions.

This is the function:

command_exists() {    # check if command exists and fail otherwise    command -v "$1" >/dev/null 2>&1    if [[ $? -ne 0 ]]; then        echo "I require $1 but it's not installed. Abort."        exit 1    fi}

You can use it in a loop to check multiple binaries:

for COMMAND in "awk" "sed" "grep" "tar" "gzip" "which" "openssl" "curl"; do    command_exists "${COMMAND}"done

If a command does not exist, your script will fail and exit with an errormessage:

I require curl but it's not installed. Abort.
Tags: bash, bash-bits, binary, command, installed, manpage, shell, snippets