70

Bash how do you capture stderr to a variable?

I would like to do something like this inside of my bash script

sh -c path/myExcecutable-bin 2>&1 =MYVARIABLE

How do you send stderror output to a variable ?

Tim Pote
  • 27,191
  • 6
  • 63
  • 65
stackoverflow
  • 18,348
  • 50
  • 129
  • 196
  • 2
    This StackOverflow [thread](http://stackoverflow.com/questions/962255/how-to-store-standard-error-in-a-variable-in-a-bash-script) should answer your question. – Web User Jun 18 '12 at 16:57
  • See one of the many related threads, and [several solutions](http://mywiki.wooledge.org/BashFAQ/002) – ormaaj Jun 18 '12 at 17:01

1 Answers1

137

To save both stdout and stderr to a variable:

MYVARIABLE="$(path/myExcecutable-bin 2>&1)"

Note that this interleaves stdout and stderr into the same variable.

To save just stderr to a variable:

MYVARIABLE="$(path/myExcecutable-bin 2>&1 > /dev/null)"
Arnavion
  • 3,627
  • 1
  • 24
  • 31
Tim Pote
  • 27,191
  • 6
  • 63
  • 65
  • 13
    I just want to note that you will save both stderr and stdout to the variable. When you need only `stderr` use `2>&1 >/dev/null` – Igor Chubin Jun 18 '12 at 16:59
  • @IgorChubin Good point. I was basing my original answer on what it looked like the OP wanted to do, but that isn't necessarily what they actually wanted. See my changes. – Tim Pote Jun 18 '12 at 17:08
  • Pretty sure that should be "`stdout` _and_ `stderr`", no? – Benjamin W. Oct 03 '16 at 20:53
  • Not sure what you mean. "`stdout` _and_ `stderr`" is literally the first sentence of the answer. – Tim Pote Oct 04 '16 at 14:25
  • Ah, I see. There was an edit. Yeah, that should have been stdout, not stdin. :) – Tim Pote Oct 04 '16 at 14:26