linux - redirect one bash line to stdout/terminal vs log

07
2014-07
  • veilig

    I have a bash script where I'm redirecting output into a file for logging.

    if test -t 1; then
        # stdout is a terminal
        exec > $OUTPUT_FILE 2>&1
    else
        # stdout is not a terminal, no logging.
        false     
    fi 
    

    I have one spot later where I actually need output to go to stdout. Is there a way to override just one call to force that?

    echo test 1>
    
  • Answers
  • bgStack

    You could put this line earlier on in your script:

    exec 3>&1
    

    Then whenever you need to send something to go to stdout:

    echo "this goes to stdout" 1>&3
    

    Cleanup:

    exec 1>&3
    echo "now goes to normal stdout"
    exec 3>&-  #to remove fd3
    

    How it works is that you define a new file descriptor, 3, and it points to the same place stdout does. You then redirect stdout as needed, but fd3 stays the same as what it was (which is your terminal). When you're done, just remove fd3!

    Edit:

    If you want output to goto both your file and "classic stdout", do this:

    echo "goes both places" | tee -a $OUTPUT_FILE 1>&3
    

  • Related Question

    linux - File redirection in bash
  • Tallow

    What's the difference between using > and >>?

    How can I use both < and > (redirection operators) in a single command?


  • Related Answers
  • Nifle

    > redirects data from stdout (read standard out) to a file.

    ls -a > my-files.txt

    will take the output of ls -a and put it into a file named my-files.txt deleting/overwriting the file if it exists. Using >> instead of > in the example above will not overwrite the file if it exists but add the output of ls -a to the end of my-files.txt

    < on the other hand sends data to a programs stdin (read standard in). If I have a file called my-files.txtand I want to know how many words it contains I can send it to a program called wc. This program accepts data on it's stdin so to the data to it I do

    wc -w < my-files.txt

    And lastly If I want to save the output of that command to a new file I can use both like so

    wc -w < my-files.txt > wordcount.txt

  • Mikhail Veltishchev

    >> means just append / create if not exists, very useful for logs.

    << also exists and useful. Try:

    $ cat > a <<EOF
    some text here
    more text
    EOF
    
    $ cat a
    

    You see that file a contains text between two EOF.