How to redirect and append both stdout and stderr to a file with Bash?

前端 未结 7 1176
春和景丽
春和景丽 2020-11-22 01:16

To redirect stdout to a truncated file in Bash, I know to use:

cmd > file.txt

To redirect stdout in Bash, appending to

相关标签:
7条回答
  • 2020-11-22 01:22

    This should work fine:

    your_command 2>&1 | tee -a file.txt
    

    It will store all logs in file.txt as well as dump them on terminal.

    0 讨论(0)
  • 2020-11-22 01:28

    I am surprised that in almost ten years, no one has posted this approach yet:

    If using older versions of bash where &>> isn't available, you also can do:

    (cmd 2>&1) >> file.txt
    

    This spawns a subshell, so it's less efficient than the traditional approach of cmd >> file.txt 2>&1, and it consequently won't work for commands that need to modify the current shell (e.g. cd, pushd), but this approach feels more natural and understandable to me:

    1. Redirect stderr to stdout.
    2. Redirect the new stdout by appending to a file.

    Also, the parentheses remove any ambiguity of order, especially if you want to pipe stdout and stderr to another command instead.

    Edit: To avoid starting a subshell, you instead could use curly braces instead of parentheses to create a group command:

    { cmd 2>&1; } >> file.txt
    

    (Note that a semicolon (or newline) is required to terminate the group command.)

    0 讨论(0)
  • 2020-11-22 01:33
    cmd >>file.txt 2>&1
    

    Bash executes the redirects from left to right as follows:

    1. >>file.txt: Open file.txt in append mode and redirect stdout there.
    2. 2>&1: Redirect stderr to "where stdout is currently going". In this case, that is a file opened in append mode. In other words, the &1 reuses the file descriptor which stdout currently uses.
    0 讨论(0)
  • 2020-11-22 01:39

    In Bash you can also explicitly specify your redirects to different files:

    cmd >log.out 2>log_error.out
    

    Appending would be:

    cmd >>log.out 2>>log_error.out
    
    0 讨论(0)
  • 2020-11-22 01:41

    In Bash 4 (as well as ZSH 4.3.11):

    cmd &>>outfile
    

    just out of box

    0 讨论(0)
  • 2020-11-22 01:42

    Try this

    You_command 1>output.log  2>&1
    

    Your usage of &>x.file does work in bash4. sorry for that : (

    Here comes some additional tips.

    0, 1, 2...9 are file descriptors in bash.

    0 stands for stdin, 1 stands for stdout, 2 stands for stderror. 3~9 is spare for any other temporary usage.

    Any file descriptor can be redirected to other file descriptor or file by using operator > or >>(append).

    Usage: <file_descriptor> > <filename | &file_descriptor>

    Please reference to http://www.tldp.org/LDP/abs/html/io-redirection.html

    0 讨论(0)
提交回复
热议问题