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

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


当前回答

$name="rsync"

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

其他回答

这个就行了。Apt-get install是幂等的。

sudo apt-get install --no-upgrade command

UpAndAdam:

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

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

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

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

这对我来说很好……

在本地而不是Docker中运行测试时,我也有类似的需求。基本上,我只想安装任何尚未安装的.deb文件。

# If there are .deb files in the folder, then install them
if [ `ls -1 *.deb 2> /dev/null | wc -l` -gt 0 ]; then
  for file in *.deb; do
    # Only install if not already installed (non-zero exit code)
    dpkg -I ${file} | grep Package: | sed -r 's/ Package:\s+(.*)/\1/g' | xargs dpkg -s
    if [ $? != 0 ]; then
        dpkg -i ${file}
    fi;
  done;
else
  err "No .deb files found in '$PWD'"
fi

我想我能看到的唯一问题是它没有检查包的版本号,所以如果.deb文件是一个更新的版本。这样就不会覆盖当前安装的包。

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

dpkg -s <packagename>

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

dpkg-query -l <packagename>

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

dpkg -S `which <command>`

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

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