我正在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和Debian的command-not-found包中。
其他回答
现在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
对于Ubuntu来说,apt提供了一种相当不错的方式来做到这一点。下面是谷歌Chrome浏览器的一个例子:
grep -qE "(已安装|upgradeable)"|| apt-get install google-chrome-stable
我将错误输出重定向为null,因为apt警告不要使用其“不稳定的cli”。我怀疑列表包是稳定的,所以我认为可以扔掉这个警告。qq让apt变得超级安静。
在本地而不是Docker中运行测试时,我也有类似的需求。基本上,我只想安装任何尚未安装的.deb文件。
# If there are .deb files in the folder, then install them
if [ `ls -1 *.deb 2> /dev/null | wc -l` -gt 0 ]; then
for file in *.deb; do
# Only install if not already installed (non-zero exit code)
dpkg -I ${file} | grep Package: | sed -r 's/ Package:\s+(.*)/\1/g' | xargs dpkg -s
if [ $? != 0 ]; then
dpkg -i ${file}
fi;
done;
else
err "No .deb files found in '$PWD'"
fi
我想我能看到的唯一问题是它没有检查包的版本号,所以如果.deb文件是一个更新的版本。这样就不会覆盖当前安装的包。
有点以你的为基础,只是更“优雅”一点。只是因为我很无聊。
#!/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