我正在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

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


当前回答

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

其他回答

$name="rsync"

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

UpAndAdam:

但是,不能简单地依赖这里的返回代码来编写脚本

根据我的经验,你可以依赖dkpg的退出代码。

如果安装了包,dpkg -s的返回码是0,如果没有,返回码是1,所以我找到的最简单的解决方案是:

dpkg -s <pkg-name> 2>/dev/null >/dev/null || sudo apt-get -y install <pkg-name>

这对我来说很好……

apt list [packagename]

这似乎是在DPKG和旧apt-*工具之外最简单的方法。

which <command>
if [ $? == 1 ]; then
    <pkg-manager> -y install <command>
fi

对于Ubuntu来说,apt提供了一种相当不错的方式来做到这一点。下面是谷歌Chrome浏览器的一个例子:

grep -qE "(已安装|upgradeable)"|| apt-get install google-chrome-stable

我将错误输出重定向为null,因为apt警告不要使用其“不稳定的cli”。我怀疑列表包是稳定的,所以我认为可以扔掉这个警告。qq让apt变得超级安静。