IT Consultant – Java, J2EE, IBM WebSphere Portal, Lotus Notes/Domino
RSS icon Home icon
  • Bash: Capturing stderr in a variable while still printing to the console.

    (2 votes) 1 Star2 Stars3 Stars4 Stars5 Stars
    Loading...
    Posted on 31 January 2011 Sebastian Thomschke*/?> No comments

    Storing the stdout output of a command in a variable and displaying it is simple:

    OUTPUT=$(command)
    echo $OUTPUT
    

    If you have longer running commands where you want to display stdout in realtime and also store it in a variable you can tee the output to stderr:

    OUTPUT=$(command | tee /dev/stderr)
    
    OUTPUT=$(command | tee /proc/self/fd/2)
    
    OUTPUT=$(command | tee >(cat - >&2))
    

    If you have longer running commands where you want to display stdout/stderr in realtime and also store stderr in a variable it gets a bit complicated.
    However, this can be achieved by switching stdout and stderr and then teeing the new stdout (which is stderr now) back to stderr for console output.

    ERROR=$(command 3>&1 1>&2 2>&3 | tee /dev/stderr)
    
    ERROR=$(command 3>&1 1>&2 2>&3 | tee /proc/self/fd/2)
    
    ERROR=$(command 3>&1 1>&2 2>&3 | tee >(cat - >&2))
    

    Good reading:
    Bash FAQ: How can I store the return value/output of a command in a variable?