我正在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
大多数人都会这么做吗?还是有更优雅的解决方案?
当前回答
有点以你的为基础,只是更“优雅”一点。只是因为我很无聊。
#!/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
其他回答
建议使用以下内容的答案:
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。
对于Ubuntu来说,apt提供了一种相当不错的方式来做到这一点。下面是谷歌Chrome浏览器的一个例子:
grep -qE "(已安装|upgradeable)"|| apt-get install google-chrome-stable
我将错误输出重定向为null,因为apt警告不要使用其“不稳定的cli”。我怀疑列表包是稳定的,所以我认为可以扔掉这个警告。qq让apt变得超级安静。
这个命令是最容易记住的:
dpkg --get-selections <package-name>
如果已经安装,它会打印:
<包名称>安装
否则它会打印
没有找到匹配<package-name>的包。
这是在Ubuntu 12.04.1 (Precise穿山甲)上测试的。
这似乎很有效。
$ sudo dpkg-query -l | grep <some_package_name> | wc -l
如果没有安装,则返回0;如果安装,则返回某个数字> 0。
which <command>
if [ $? == 1 ]; then
<pkg-manager> -y install <command>
fi