5

I have this code that produces an error, and it works to supress the STDOUT but it doesnt store the STDERR in the variable ERROR.

ERROR = $(memtester 900 1 > /dev/null)
Aaron
  • 759
  • 1
  • 7
  • 15
  • you can't have spaces around `=` in a shell variable assignment. – Barmar Mar 01 '17 at 23:12
  • And you shouldn't use uppercase variable names, those are reserved for application environment variables. – Barmar Mar 01 '17 at 23:13
  • Redirect stderr to stdout is done by 2>&1, & is used to follow a file descriptor. So the following code should work for you. `ERROR=$({ memtester 900 > /dev/null; } 2>&1` – rowan Mar 01 '17 at 23:24

1 Answers1

9

You can capture it like this:

error=$(memtester 900 1 2>&1 >/dev/null)

order of redirection operators is important here.

  • 2>&1 - redirects stderr to stdout
  • >/dev/null - redirects stdout to /dev/null
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • why do we need the redirection to /dev/null? Won't that lose the output? – djna Mar 01 '17 at 23:17
  • 3
    @djna Normal output will be lost indeed, but obviously by OP the point is to capture only the command error (if any). Without `>/dev/null` this variable will contain also the ouput. – George Vasiliou Mar 01 '17 at 23:30
  • @user2489314: Did this work for you? – anubhava Mar 02 '17 at 06:32
  • @George Vasilou but stderr has been redirected to stdout, so stderr output is sent to /dev/null too. As this stands the error variable will contain nothing. – djna Mar 02 '17 at 07:41
  • 3
    @djna - No , This is not how redirection works. The command `2>&1' does not mean follow the &1 (stdout). Means send the fd 2 (stderr) to wherever fd1 CURRENTLY goes = command (pipe) buffer or /dev/tty if run directly from CLI. If you later redirect fd1 to somewhere else (a file or like in this answer to dev/null), fd2 still goes to the device which fd1 was bound before (command pipe or /dev/tty in command line). It is very well explained here : http://mywiki.wooledge.org/BashFAQ/002 – George Vasiliou Mar 02 '17 at 07:58
  • 2
    @George Vasilou Aha! Thanks George. (There was a time when I knew this stuff ;-) – djna Mar 02 '17 at 08:07