简体   繁体   中英

Bash. stdout from background piped commands

I don't know how to recover the stdout of commands "piped" launched in background. Let's explain. I have this command:

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

And i want to send all to the background to recover the pid using $!, but when i put & anywhere, the grep stop working and the iface var is empty. Any idea? Thank you.

If you want to just get status that the script is still running while waiting for the output from grep you can use an existing tool like pv that will print a progress meter to stderr so it won't interfere with your capturing the output.

Failing that, you could write a function that would be slower than the pv solution I imagine, but will let you update the spinner after, say, each line like

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)

or you could have your backgrounded command write to a temporary file and get the answer after like

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

or perhaps you wouldn't even need it in a variable any more as many things know how to operate on files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM