我正在编写一个脚本来检查非常大的依赖项列表。因此,我编写了一个函数,该函数将包名称作为输入,并使用dpkg
检查它是否已安装并打印适当的输出。以下是该函数的一个版本:
check_dependency() {
dpkg -l $1 > /dev/null
if [ $? -eq 0 ]; then
# print something saying it is installed
else
# print something saying it was not found
fi
}
当软件包安装后,它可以正常工作。但是当软件包未安装时,它不知何故不会将输出重定向到/dev/null
并提示:
dpkg-query: no packages found matching foo-bar
在第二次尝试中,我修改了函数主体以便使用它grep -q
:
check_dependency() {
dpkg -s $1 | grep -q 'installed'
if [ $? -eq 0 ]; then
# print something saying it is installed
else
# print something saying it was not found
fi
}
当安装该包时,它再次看起来工作正常,但是,当找不到包并且dpkg
终端上出现不需要的消息时:
dpkg-query: package 'foo-bar' is not installed and no information is available bla bla...
直接使用dpkg-query
会导致类似的问题。当无法找到包时,如何让它保持静默?
答案1
您希望将标准输出 (stdout) 和标准错误 (stderr) 都重定向到/dev/null
。为此,请用 替换>
。&>
这是 特有的快捷方式bash
。因此您的代码将是:
check_dependency() {
dpkg -l $1 &> /dev/null
if [ $? -eq 0 ]; then
# print something saying it is installed
else
# print something saying it was not found
fi
}
但是,如果软件包已被删除但配置文件仍然存在(如@AB 所指出的),则仍会将该软件包视为已安装。相反,您可以尝试
check_dependency() {
# Get the number of packages installed that match $1
num=$(dpkg -l "$1" 2>/dev/null | egrep '^ii' | wc -l)
if [ $num -eq 1 ]; then
# print something saying it is installed
elif [ $num -gt 1]; then
# print something saying there is more than one package matching $1
else
# print something saying it was not found
fi
}
答案2
使用dpkg -l $1
并检查返回代码说没有什么关于包的安装状态。
使用awk
和dpkg -l
检查状态ii
dpkg -l | awk '/^ii +'"$1"' +/'
例子
$ package="mc"
$ dpkg -l | awk '/^ii +'"$package" +' /'
ii mc 3:4.8.13-3 i386 Midnight Commander - a powerful file manager
$ package="foobar"
$dpkg -l | awk '/^ii +'"$package" +' /'
<returns nothing>
或者
$ package="mc"
$ dpkg -l | awk '/^ii +'"$package"' +/ {print $2}'
mc