0

I noticed that when trying to capture output of a command to a bash variable, some lines are not captured at all, although they are printed on the terminal when variable assigning is not done. One example is ssh-keyscan, when banner messages are enabled. Another example is access logs from a Python SimpleHTTPServer.

How are these getting printed on the terminal but not captured to a variable?

chamilad
  • 1,619
  • 3
  • 23
  • 40
  • 5
    Because they are not sent to `stdout` but to `stderr`. See for example `ls laajalkdjlajfk` and `echo "hello"`. The former writes to `stderr`, while the latter to `stdout`. – fedorqui May 09 '16 at 12:35
  • That makes sense. Although, in the Python HTTP server's case, even when I've redirected 2>&1 to /dev/null the request logs are displayed in the terminal. – chamilad May 09 '16 at 12:52
  • I see. You should give specific details on where and how you are using it to make us fully understand your question. – fedorqui May 09 '16 at 12:53
  • Standard output and standard error are not the only possible file descriptors. However, it is more likely that you wrote something like `2>&1 > /dev/null` instead of `> /dev/null 2>&1`, which is what directs both to `/dev/null`. – chepner May 09 '16 at 13:40
  • OUTPUT=$({ ERROR=$(cmd.sh 2>&1 1>&$TMP_FD); } {TMP_FD}>&1) this will capture both stderr and stdout in different variables, and let you see the status – kdubs Dec 03 '21 at 21:20

1 Answers1

4

Probably fedorqui have a reason in his comment...

And in this case you could redirect stderr to stdout using redirect option 2>&1. Like this :

toto=$( ls tioto 2>&1 )
echo $toto
ls: cannot access tioto: No such file or directory
Paul Zakharov
  • 515
  • 2
  • 15