To redirect stdout to a truncated file in Bash, I know to use:
cmd > file.txt
To redirect stdout in Bash, appending to
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:
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.)