linux - 如何限制在循环中执行的命令的 shell 脚本中的输出

标签 linux shell scripting ubuntu-16.04

我有一个 shell 脚本如下

#!/usr/bin/env bash


#Packages list

declare -a packages=( git build_essential node )
declare -a packages_status

# installing=`apt-get install -y `
installing="echo "

for i in "${packages[@]}"
do
    packages_status[$i]=$(dpkg-query -W -f='${status}' $i | grep "install ok installed")
    # echo ${packages_status[$i]}
done

代码行

packages_status[$i]=$(dpkg-query -W -f='${status}' $i | grep "install ok installed")

产生以下输出

dpkg-query: no packages found matching build_essential

dpkg-query: no packages found matching node

我希望 LOC 在不产生任何输出的情况下执行。

最佳答案

dpkg-query 命令将错误输出到 stderr,而不是 stdout。
因此,您应该在管道传输到 grep 之前链接这两个 channel :

packages_status[$i]=$(dpkg-query -W -f='${status}' $i 2>&1 | grep "install ok installed")

这样脚本只会为已安装的包打印“install ok installed”行。

关于linux - 如何限制在循环中执行的命令的 shell 脚本中的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55160109/

相关文章:

jquery - 使用 jquery ajax 或 post 插入 DOM 时如何停止评估脚本标签

python - "scripting"vim 使用更细粒度的 python

linux - Amazon EC2 - Apache 服务器重启问题

Linux:在脚本中运行二进制文件

mongodb - IPTables 问题 : Can't connect to mongodb w/mongo shell - CentOS

scripting - 所有脚本都是用脚本语言编写的吗?

c# - Compact Framework 的脚本库

php - 将 wget 与 shell_exec 和 at 命令一起使用?

linux - Linux 和 Unix 有什么区别?

从 Shell 文件启动时 Python 脚本无法运行,但从终端启动时可以运行