我正在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
大多数人都会这么做吗?还是有更优雅的解决方案?
当前回答
既然你提到了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替换。
其他回答
有点以你的为基础,只是更“优雅”一点。只是因为我很无聊。
#!/bin/bash
FOUND=("\033[38;5;10m")
NOTFOUND=("\033[38;5;9m")
PKG="${@:1}"
command ${PKG} &>/dev/null
if [[ $? != 0 ]]; then
echo -e "${NOTFOUND}[!] ${PKG} not found [!]"
echo -e "${NOTFOUND}[!] Would you like to install ${PKG} now ? [!]"
read -p "[Y/N] >$ " ANSWER
if [[ ${ANSWER} == [yY] || ${ANSWER} == [yY][eE][sS] ]]; then
if grep -q "bian" /etc/os-release; then
sudo apt-get install ${PKG}
elif grep -q "arch" /etc/os-release; then
if [[ -f /bin/yay ]] || [[ -f /bin/yaourt ]]; then
yaourt -S ${PKG} 2>./err || yay -S ${PKG} 2>./err
else
sudo pacman -S ${PKG}
fi
elif grep -q "fedora" /etc/os-release; then
sudo dnf install ${PKG}
else
echo -e "${NOTFOUND}[!] This script couldn't detect your package manager [!]"
echo -e "${NOTFOUND}[!] Manually install it [!]"
fi
elif [[ ${ANSWER} == [nN] || ${ANSWER} == [nN][oO] ]]; then
echo -e "${NOTFOUND}[!] Exiting [!]"
fi
else
echo -e "${FOUND}[+] ${PKG} found [+]"
fi
这个就行了。Apt-get install是幂等的。
sudo apt-get install --no-upgrade command
建议使用以下内容的答案:
dpkg-query --showformat '${db:Status-Status}\n' --show $package | grep -q '^installed$'
dpkg-query --showformat '${Status}\n' --show $package | grep -q '^install ok installed$'
是正确的。
但是如果你已经安装了dpkg-dev包,你不只是想检查一个包是否安装了,你还需要:
想知道一个包是否安装在某个版本 希望在特定的体系结构中拥有一个包 查看是否提供了虚拟包
然后你可以滥用dpkg-checkbuilddeps工具来完成这项工作:
dpkg-checkbuilddeps -d apt /dev/null
这将检查是否安装了apt。
下面将检查apt是否至少在2.3.15版本中安装,grep是否作为amd64安装,并且某些已安装的包中提供了虚拟包x-window-manager:
dpkg-checkbuilddeps -d 'apt (>= 2.3.15), grep:amd64, x-window-manager' /dev/null
dpkg-checkbuilddeps的退出状态将告诉脚本依赖项是否满足。由于此方法支持传递多个包,因此即使希望检查是否安装了多个包,也只需运行一次dpkg-checkbuilddeps。
要检查是否安装了packagename,输入:
dpkg -s <packagename>
您还可以使用dpkg-query,它的输出更简洁,而且还接受通配符。
dpkg-query -l <packagename>
要找到哪个包拥有该命令,请尝试:
dpkg -S `which <command>`
有关更多详细信息,请参见文章“了解Linux中是否安装了软件包”和dpkg备忘单。
我发现在之前的答案中,如果安装了一个包,然后删除了它,但是安装包仍然在系统上,那么所有的解决方案都可能产生假阳性。
复制:
安装包apt-get Install curl 删除包apt-get删除卷曲
现在测试一下前面的答案。
下面的命令似乎可以解决这个问题:
dpkg-query -W -f='${Status}\n' curl | head -n1 | awk '{print $3;}' | grep -q '^installed$'
这将导致最终安装或不安装。