How can I check if a program exists from a Bash script?

后端 未结 30 2113
有刺的猬
有刺的猬 2020-11-21 07:21

How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?

It seems like it should be easy, but it\

30条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 08:01

    My setup for a Debian server:

    I had the problem when multiple packages contained the same name.

    For example apache2. So this was my solution:

    function _apt_install() {
        apt-get install -y $1 > /dev/null
    }
    
    function _apt_install_norecommends() {
        apt-get install -y --no-install-recommends $1 > /dev/null
    }
    function _apt_available() {
        if [ `apt-cache search $1 | grep -o "$1" | uniq | wc -l` = "1" ]; then
            echo "Package is available : $1"
            PACKAGE_INSTALL="1"
        else
            echo "Package $1 is NOT available for install"
            echo  "We can not continue without this package..."
            echo  "Exitting now.."
            exit 0
        fi
    }
    function _package_install {
        _apt_available $1
        if [ "${PACKAGE_INSTALL}" = "1" ]; then
            if [ "$(dpkg-query -l $1 | tail -n1 | cut -c1-2)" = "ii" ]; then
                 echo  "package is already_installed: $1"
            else
                echo  "installing package : $1, please wait.."
                _apt_install $1
                sleep 0.5
            fi
        fi
    }
    
    function _package_install_no_recommends {
        _apt_available $1
        if [ "${PACKAGE_INSTALL}" = "1" ]; then
            if [ "$(dpkg-query -l $1 | tail -n1 | cut -c1-2)" = "ii" ]; then
                 echo  "package is already_installed: $1"
            else
                echo  "installing package : $1, please wait.."
                _apt_install_norecommends $1
                sleep 0.5
            fi
        fi
    }
    

提交回复
热议问题