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?

  • Determine the user who logged on via SSH

    1 Star2 Stars3 Stars4 Stars5 Stars
    Loading...
    Posted on 23 February 2009 Sebastian Thomschke*/?> No comments

    Today we had the need to determine the initial id of a user who logged onto a Linux box via SSH and executed the su command. When the su command is issued the effective user is changed and whoami or id commands will report that new user id instead.

    For anyone who is interested, that is what we came up to put the initial user id into a variable named ${LOGIN_USER}

    LOGIN_USER=`who -m`; LOGIN_USER=${LOGIN_USER%% *}

    or alternatively

    LOGIN_USER=`who -m | cut -d' ' -f1`