Laine Mikael Laine Mikael - 2 months ago 5x
Bash Question

How to consistently record command output in a variable in UNIX

In some cases what I see in a console output is different from what I get recorded after redirection. I see this on Linux/bash but this example is ksh/OpenBSD. Is there a way around this?

For example:

# pfctl -ttable -Ttest > result.txt
0/1 addresses match.
# more result.txt
result.txt (END)

In other words the "0/1 addresses match." is printed on the console, but I cannot for the life of me get it into a file, variable or anything. I've used $() and > which work for most commands, but every now and then there is a command that spits out stuff on the screen but I get nothing via the redirect/pipe. I hope someone can shed light on this peculiarity.

So again contrast this:

# OUTP=$(pfctl -tscanners -Ttest
0/1 addresses match.
# echo $OUTP


(nothing echoing, the variable does not hold the console output) with this:

# OUTP=$(date)
# echo $OUTP
Sun Aug 21 08:33:37 PDT 2016

(the variable contains the entire console output)

Thanks again for any help.


Your command has 2 different output streams.
You need to rederict the second (stderr) to the first.

pfctl -ttable -Ttest > result.txt 2>&1