我正在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系统上工作,目前我正在做的是:
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
大多数人都会这么做吗?还是有更优雅的解决方案?
当前回答
我发现在之前的答案中,如果安装了一个包,然后删除了它,但是安装包仍然在系统上,那么所有的解决方案都可能产生假阳性。
复制:
安装包apt-get Install curl 删除包apt-get删除卷曲
现在测试一下前面的答案。
下面的命令似乎可以解决这个问题:
dpkg-query -W -f='${Status}\n' curl | head -n1 | awk '{print $3;}' | grep -q '^installed$'
这将导致最终安装或不安装。
其他回答
为了更明确一点,这里有一些Bash脚本,用于检查包并在需要时安装它。当然,您可以在发现包丢失时执行其他操作,例如简单地使用错误代码退出。
REQUIRED_PKG="some-package"
PKG_OK=$(dpkg-query -W --showformat='${Status}\n' $REQUIRED_PKG|grep "install ok installed")
echo Checking for $REQUIRED_PKG: $PKG_OK
if [ "" = "$PKG_OK" ]; then
echo "No $REQUIRED_PKG. Setting up $REQUIRED_PKG."
sudo apt-get --yes install $REQUIRED_PKG
fi
如果脚本在GUI中运行(例如,它是一个Nautilus脚本),您可能想要用'gksudo'调用替换'sudo'调用。
UpAndAdam:
但是,不能简单地依赖这里的返回代码来编写脚本
根据我的经验,你可以依赖dkpg的退出代码。
如果安装了包,dpkg -s的返回码是0,如果没有,返回码是1,所以我找到的最简单的解决方案是:
dpkg -s <pkg-name> 2>/dev/null >/dev/null || sudo apt-get -y install <pkg-name>
这对我来说很好……
既然你提到了Ubuntu,而且你想以编程的方式做到这一点(虽然也可以使用dpkg的变体,但实现起来会更复杂),这(这)肯定是可行的:
#!/bin/bash
pkgname=mutt
which $pkgname > /dev/null;isPackage=$?
if [ $isPackage != 0 ];then
echo "$pkgname not installed"
sleep 1
read -r -p "${1:-$pkgname will be installed. Are you sure? [y/N]} " response
case "$response" in
[yY][eE][sS]|[yY])
sudo apt-get install $pkgname
;;
*)
false
;;
esac
else
echo "$pkgname is installed"
sleep 1
fi
尽管为了POSIX兼容性,您可能希望使用命令-v,正如在另一个类似问题中提到的那样。
这样的话, 在上面的代码示例中,$pkgname > /dev/null应该被命令-v $pkgname替换。
这个特性已经存在于Ubuntu和Debian的command-not-found包中。
which <command>
if [ $? == 1 ]; then
<pkg-manager> -y install <command>
fi