Search code examples
bashstdoutstderr

Bash: Pipe stdout and catch stderr into a variable


Is it possible to pipe normal stdout further to another program, but store stderr into a variable?

This is the usecase:

mysqldump database | gzip > database.sql

In this scenario I would like to catch all errors/warnings produced by mysqldump and store them into a variable, but the normal stdout (which is the dump) should continue being piped to gzip.

Any ideas about how to accomplish this?


Solution

  • You could do something like:

    errors=$(mysqldump database 2>&1 > >(gzip > database.sql))
    

    Here, I'm using process substitution to get gzip to use mysqldump's output as stdin. Given the order of redirections (2>&1 before >), mysqldump's stderr should now be used for the command substitution.

    Testing it out:

    $ a=$(sh -c 'echo foo >&2; echo bar' 2>&1 > >(gzip > foo))
    $ gunzip < foo
    bar
    $ echo $a
    foo