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

Bash. stdout from background piped commands

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

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

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

如果您只想在等待 grep 的输出时获得脚本仍然是 运行 的状态,您可以使用现有的工具 pv 来打印进度米到 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)

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