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

前端 未结 7 1178
春和景丽
春和景丽 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:43

    There are two ways to do this, depending on your Bash version.

    The classic and portable (Bash pre-4) way is:

    cmd >> outfile 2>&1
    

    A nonportable way, starting with Bash 4 is

    cmd &>> outfile
    

    (analog to &> outfile)

    For good coding style, you should

    • decide if portability is a concern (then use classic way)
    • decide if portability even to Bash pre-4 is a concern (then use classic way)
    • no matter which syntax you use, not change it within the same script (confusion!)

    If your script already starts with #!/bin/sh (no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.

    Also remember that Bash 4 &>> is just shorter syntax — it does not introduce any new functionality or anything like that.

    The syntax is (beside other redirection syntax) described here: http://bash-hackers.org/wiki/doku.php/syntax/redirection#appending_redirected_output_and_error_output

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