我不知道如何恢复在后台启动的“管道”命令的标准输出。让我们解释一下。我有这个命令:
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/