bash 。来自后台管道命令的标准输出

标签 bash background pipe stdout

我不知道如何恢复在后台启动的“管道”命令的标准输出。让我们解释一下。我有这个命令:

iface=$(airmon-ng start wlan0 2> /dev/null | grep monitor)

我想将所有内容发送到后台以使用 $! 恢复 pid,但是当我将 & 放在任何地方时,grep 停止工作并且 iface var 为空。任何想法?谢谢。

最佳答案

如果你只想在等待 grep 的输出时获取脚本仍在运行的状态,你可以使用现有的工具,如 pv ,它将打印进度meter 到 stderr,这样它就不会干扰您捕获输出。

否则,您可以编写一个比我想象的 pv 解决方案慢的函数,但会让您在每一行之后更新微调器,例如

get_monitor() {
    printf ' ' >&2 # to put a first char there to backspace the spinner over
    while read -r line; do
        if [[ $line =~ monitor ]]; then
            printf '%s\n' "$line"
        fi
        update_spinner
    done < <(airmon-ng start wlan0 2>/dev/null)
}

sp_ind=0
sp_chars='/-\|'
sp_num=${#sp_chars}
update_spinner() {
    printf '\b%s' "${sp_chars:sp_ind++%sp_num:1}" >&2
}

iface=$(get_monitor)

或者你可以让你的后台命令写入一个临时文件并在点赞后得到答案

airmon-ng start wlan2 2>/dev/null >/tmp/airmon_out &
# your spinner stuff
iface=$(cat /tmp/airmon_out)

或者也许你甚至不再需要它在变量中,因为很多东西都知道如何对文件进行操作

关于 bash 。来自后台管道命令的标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37373784/

相关文章:

linux - 如何使用 AWK 或 SED 为文件中的每一行生成 UUID?

jquery - 为来自 jQuery 的伪元素应用 CSS 样式

c - Pipe() fork() 和 exec

c - sem_open 不适用于 Ubuntu : undefined reference to `sem_open'

linux - 将 wget 与 OpenID 登录结合使用

bash - 如何在 bash 中转换 CSV 文件?

android - 如何检查 View 是否设置了特定背景

javascript - 向页面添加内容会弄乱背景

c - 在 C 中多次从 stdin 读取相同的数据

bash - 使用 bash 查找函数的声明和定义