我正在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
大多数人都会这么做吗?还是有更优雅的解决方案?
当前回答
我使用这个解决方案,因为我发现它是最直接的。
function must_install(){
return "$(apt -qq list $var --installed 2> /dev/null |wc -l)"
}
function install_if() {
unset install
for var in "$@"
do
if $(must_install $var)
then
install+="${var} "
fi
done
if [ -n "$install" ];
then
sudo apt-get install -qy $install
fi
}
整洁的事情是,must_install返回1或0,然后通过调用if将其解释为true或false,因此我们不需要使用[]进行任何测试。
Install_if接受按空格分隔的任意数量的包。
问题是apt并不打算在脚本中使用,因此这可能在任何时候停止工作。8)
其他回答
我使用这个解决方案,因为我发现它是最直接的。
function must_install(){
return "$(apt -qq list $var --installed 2> /dev/null |wc -l)"
}
function install_if() {
unset install
for var in "$@"
do
if $(must_install $var)
then
install+="${var} "
fi
done
if [ -n "$install" ];
then
sudo apt-get install -qy $install
fi
}
整洁的事情是,must_install返回1或0,然后通过调用if将其解释为true或false,因此我们不需要使用[]进行任何测试。
Install_if接受按空格分隔的任意数量的包。
问题是apt并不打算在脚本中使用,因此这可能在任何时候停止工作。8)
如果只使用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
Use:
apt-cache policy <package_name>
如果没有安装,它将显示:
Installed: none
否则它将显示:
Installed: version
这个特性已经存在于Ubuntu和Debian的command-not-found包中。
which <command>
if [ $? == 1 ]; then
<pkg-manager> -y install <command>
fi