我正在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$'
这将导致最终安装或不安装。
其他回答
对于Ubuntu来说,apt提供了一种相当不错的方式来做到这一点。下面是谷歌Chrome浏览器的一个例子:
grep -qE "(已安装|upgradeable)"|| apt-get install google-chrome-stable
我将错误输出重定向为null,因为apt警告不要使用其“不稳定的cli”。我怀疑列表包是稳定的,所以我认为可以扔掉这个警告。qq让apt变得超级安静。
我发现在之前的答案中,如果安装了一个包,然后删除了它,但是安装包仍然在系统上,那么所有的解决方案都可能产生假阳性。
复制:
安装包apt-get Install curl 删除包apt-get删除卷曲
现在测试一下前面的答案。
下面的命令似乎可以解决这个问题:
dpkg-query -W -f='${Status}\n' curl | head -n1 | awk '{print $3;}' | grep -q '^installed$'
这将导致最终安装或不安装。
这个就行了。Apt-get install是幂等的。
sudo apt-get install --no-upgrade command
我使用以下方法:
which mySQL 2>&1|tee 1> /dev/null
if [[ "$?" == 0 ]]; then
echo -e "\e[42m MySQL already installed. Moving on...\e[0m"
else
sudo apt-get install -y mysql-server
if [[ "$?" == 0 ]]; then
echo -e "\e[42mMy SQL installed\e[0m"
else
echo -e "\e[42Installation failed\e[0m"
fi
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;