我正在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似乎有一个选项——不升级,只做OP想要的:
——no-upgrade不升级包。当与install一起使用时,no-upgrade将阻止已经安装的包被升级。
Manpage来自https://linux.die.net/man/8/apt-get
因此你可以使用
apt-get install --no-upgrade package
如果不是,包才会被安装。
其他回答
有点以你的为基础,只是更“优雅”一点。只是因为我很无聊。
#!/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
如果只使用awk安装了else 1,则显式打印0:
dpkg-query -W -f '${Status}\n' 'PKG' 2>&1|awk '/ok installed/{print 0;exit}{print 1}'
或者如果你喜欢另一种方式,1表示安装,0表示:
dpkg-query -W -f '${Status}\n' 'PKG' 2>&1|awk '/ok installed/{print 1;exit}{print 0}'
**用您的包名替换PKG
便利功能:
installed() {
return $(dpkg-query -W -f '${Status}\n' "${1}" 2>&1|awk '/ok installed/{print 0;exit}{print 1}')
}
# usage:
installed gcc && echo Yes || echo No
#or
if installed gcc; then
echo yes
else
echo no
fi
apt list [packagename]
这似乎是在DPKG和旧apt-*工具之外最简单的方法。
UpAndAdam:
但是,不能简单地依赖这里的返回代码来编写脚本
根据我的经验,你可以依赖dkpg的退出代码。
如果安装了包,dpkg -s的返回码是0,如果没有,返回码是1,所以我找到的最简单的解决方案是:
dpkg -s <pkg-name> 2>/dev/null >/dev/null || sudo apt-get -y install <pkg-name>
这对我来说很好……
所有的答案都很好,但是对于像我这样的初学者来说似乎很复杂。这就是对我有效的解决方案。我的Linux环境是centOS,但不能确定它适用于所有发行版
PACKAGE_NAME=${PACKAGE_NAME:-node}
if ! command -v $PACKAGE_NAME > /dev/null; then
echo "Installing $PACKAGE_NAME ..."
else
echo "$PACKAGE_NAME already installed"
fi