我正在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
大多数人都会这么做吗?还是有更优雅的解决方案?
当前回答
这个命令是最容易记住的:
dpkg --get-selections <package-name>
如果已经安装,它会打印:
<包名称>安装
否则它会打印
没有找到匹配<package-name>的包。
这是在Ubuntu 12.04.1 (Precise穿山甲)上测试的。
其他回答
这个就行了。Apt-get install是幂等的。
sudo apt-get install --no-upgrade command
现在apt-get似乎有一个选项——不升级,只做OP想要的:
——no-upgrade不升级包。当与install一起使用时,no-upgrade将阻止已经安装的包被升级。
Manpage来自https://linux.die.net/man/8/apt-get
因此你可以使用
apt-get install --no-upgrade package
如果不是,包才会被安装。
这一行代码为“nano”包返回1(已安装)或0(未安装)…
$(dpkg-query -W -f='${Status}' nano 2>/dev/null | grep -c "ok installed")
即使包不存在或不可用。
下面的例子将安装'nano'包,如果它没有安装…
if [ $(dpkg-query -W -f='${Status}' nano 2>/dev/null | grep -c "ok installed") -eq 0 ];
then
apt-get install nano;
fi
这似乎很有效。
$ sudo dpkg-query -l | grep <some_package_name> | wc -l
如果没有安装,则返回0;如果安装,则返回某个数字> 0。
我使用这个解决方案,因为我发现它是最直接的。
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)