How to redirect output to a file and stdout

后端 未结 10 1343
借酒劲吻你
借酒劲吻你 2020-11-22 08:11

In bash, calling foo would display any output from that command on the stdout.

Calling foo > output would redirect any output from that

相关标签:
10条回答
  • 2020-11-22 08:42

    Something to add ...

    The package unbuffer has support issues with some packages under fedora and redhat unix releases.

    Setting aside the troubles

    Following worked for me

    bash myscript.sh 2>&1 | tee output.log
    

    Thank you ScDF & matthew your inputs saved me lot of time..

    0 讨论(0)
  • 2020-11-22 08:43

    tee is perfect for this, but this will also do the job

    ls -lr / > output | cat output
    
    0 讨论(0)
  • 2020-11-22 08:44

    Another way that works for me is,

    <command> |& tee  <outputFile>
    

    as shown in gnu bash manual

    Example:

    ls |& tee files.txt
    

    If ‘|&’ is used, command1’s standard error, in addition to its standard output, is connected to command2’s standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error to the standard output is performed after any redirections specified by the command.

    For more information, refer redirection

    0 讨论(0)
  • 2020-11-22 08:44

    You can do that for your entire script by using something like that at the beginning of your script :

    #!/usr/bin/env bash
    
    test x$1 = x$'\x00' && shift || { set -o pipefail ; ( exec 2>&1 ; $0 $'\x00' "$@" ) | tee mylogfile ; exit $? ; }
    
    # do whaetever you want
    

    This redirect both stderr and stdout outputs to the file called mylogfile and let everything goes to stdout at the same time.

    It is used some stupid tricks :

    • use exec without command to setup redirections,
    • use tee to duplicates outputs,
    • restart the script with the wanted redirections,
    • use a special first parameter (a simple NUL character specified by the $'string' special bash notation) to specify that the script is restarted (no equivalent parameter may be used by your original work),
    • try to preserve the original exit status when restarting the script using the pipefail option.

    Ugly but useful for me in certain situations.

    0 讨论(0)
  • 2020-11-22 08:45

    Using tail -f output should work.

    0 讨论(0)
  • 2020-11-22 08:48

    < command > |& tee filename # this will create a file "filename" with command status as a content, If a file already exists it will remove existed content and writes the command status.

    < command > | tee >> filename # this will append status to the file but it doesn't print the command status on standard_output (screen).

    I want to print something by using "echo" on screen and append that echoed data to a file

    echo "hi there, Have to print this on screen and append to a file" 
    
    0 讨论(0)
提交回复
热议问题