我正在Ubuntu系统上工作,目前我正在做的是:

if ! which command > /dev/null; then
   echo -e "Command not found! Install? (y/n) \c"
   read
   if "$REPLY" = "y"; then
      sudo apt-get install command
   fi
fi

大多数人都会这么做吗?还是有更优雅的解决方案?


当前回答

这似乎很有效。

$ sudo dpkg-query -l | grep <some_package_name> | wc -l

如果没有安装,则返回0;如果安装,则返回某个数字> 0。

其他回答

$name="rsync"

[ `which $name` ] $$ echo "$name : installed" || sudo apt-get install -y $name

这个特性已经存在于Ubuntu和Debian的command-not-found包中。

我使用这个解决方案,因为我发现它是最直接的。

function must_install(){
   return "$(apt -qq list $var --installed 2> /dev/null |wc -l)"
}

function install_if() {
    unset install
    for var in "$@"
    do
        if $(must_install $var)
        then
            install+="${var} "
        fi
    done
    if [ -n "$install" ];
    then
        sudo apt-get install -qy $install
    fi
}

整洁的事情是,must_install返回1或0,然后通过调用if将其解释为true或false,因此我们不需要使用[]进行任何测试。

Install_if接受按空格分隔的任意数量的包。

问题是apt并不打算在脚本中使用,因此这可能在任何时候停止工作。8)

如果只使用awk安装了else 1,则显式打印0:

dpkg-query -W -f '${Status}\n' 'PKG' 2>&1|awk '/ok installed/{print 0;exit}{print 1}'

或者如果你喜欢另一种方式,1表示安装,0表示:

dpkg-query -W -f '${Status}\n' 'PKG' 2>&1|awk '/ok installed/{print 1;exit}{print 0}'

**用您的包名替换PKG

便利功能:

installed() {
    return $(dpkg-query -W -f '${Status}\n' "${1}" 2>&1|awk '/ok installed/{print 0;exit}{print 1}')
}


# usage:
installed gcc && echo Yes || echo No

#or

if installed gcc; then
    echo yes
else
    echo no
fi

要检查是否安装了packagename,输入:

dpkg -s <packagename>

您还可以使用dpkg-query,它的输出更简洁,而且还接受通配符。

dpkg-query -l <packagename>

要找到哪个包拥有该命令,请尝试:

dpkg -S `which <command>`

有关更多详细信息,请参见文章“了解Linux中是否安装了软件包”和dpkg备忘单。