我正在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
大多数人都会这么做吗?还是有更优雅的解决方案?
当前回答
这一行代码为“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
其他回答
要检查是否安装了packagename,输入:
dpkg -s <packagename>
您还可以使用dpkg-query,它的输出更简洁,而且还接受通配符。
dpkg-query -l <packagename>
要找到哪个包拥有该命令,请尝试:
dpkg -S `which <command>`
有关更多详细信息,请参见文章“了解Linux中是否安装了软件包”和dpkg备忘单。
我使用这个解决方案,因为我发现它是最直接的。
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)
这一行代码为“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
如果您的包具有命令行接口,则可以在安装之前通过调用它的命令行工具来计算输出,从而检查包是否存在。
这里有一个叫做helm的包的例子。
#!/bin/bash
# Call the command for the package silently
helm > /dev/null
# Get the exit code of the last command
command_exit_code="$(echo $?)"
# Run installation if exit code is not equal to 0
if [ "$command_exit_code" -ne "0" ]; then
# Package does not exist: Do the package installation
else
echo "Skipping 'helm' installation: Package already exists"
fi;
这个特性已经存在于Ubuntu和Debian的command-not-found包中。