Find the answer to your Linux question:
Results 1 to 4 of 4
It's simple to redirect stdout and/or stderr to a file from within a script with, e.g. "exec 1>/tmp/outfile 2>&1". But if I want later in the script to return one ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Linux Enthusiast Mudgen's Avatar
    Join Date
    Feb 2007
    Location
    Virginia
    Posts
    664

    Bash: Redirect stdout/stderr to file, then back to screen?


    It's simple to redirect stdout and/or stderr to a file from within a script with, e.g. "exec 1>/tmp/outfile 2>&1". But if I want later in the script to return one or both to default (the screen), is there a way to do that?

  2. #2
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    How about this?

    Code:
    #!/bin/bash
    
    exec 1>/tmp/logfile.txt 2>&1
    echo hi logfile
    echo errors to logfile too >&2
    
    exec >/dev/tty 2>&1
    echo hi tty
    echo errors to tty too >&2
    Edit: see this informative stackoverflow thread
    Last edited by atreyu; 11-20-2012 at 12:55 AM. Reason: link

  3. #3
    Linux Enthusiast Mudgen's Avatar
    Join Date
    Feb 2007
    Location
    Virginia
    Posts
    664
    Thanks much, Atreyu. I'm scripting to do CIS Red Hat EL5 benchmark hardening on our installed base, and I'm seeing spots from writing awk expressions for days. /dev/tty had plumb eluded me.

  4. $spacer_open
    $spacer_close
  5. #4
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    Quote Originally Posted by Mudgen View Post
    Thanks much, Atreyu. I'm scripting to do CIS Red Hat EL5 benchmark hardening on our installed base, and I'm seeing spots from writing awk expressions for days.
    heh, i've been in similar Perl sand-storms.

    /dev/tty had plumb eluded me.
    it had eluded me too. i was thinking that you could use the output of the tty command (e.g., /dev/pts/1) to do that, but that led me to the SO link and the /dev/tty trick.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •