Skip to main content

Bash function to check if command/program exists in the current environment.

#!/usr/bin/env bash

command_exists() {
    type "$1" &> /dev/null
}

#
# Example usage:

echoerr() {
    echo "$@" 1>&2
}

open_in_browser() {
    if command_exists xdg-open; then
        xdg-open "$@"
    elif command_exists open; then
        open "$@"
    elif command_exists google-chrome; then
        google-chrome "$@"
    elif command_exists firefox; then
        firefox "$@"
    fi
}

open_command_or_exit() {
    if ! command_exists curl; then
        echoerr "You need to install curl before using this program."
        echoerr "Please refer to https://curl.haxx.se for installation instructions."
        exit 66
    fi
}

open_in_browser "https://example.com"
open_command_or_exit