To redirect and append both standard output (stdout) and standard error (stderr) to a file in Bash, use one of the following methods:
Method 1: Explicit Redirection (POSIX-compliant)
command >> file.txt 2>&1
>> file.txt: Appends stdout tofile.txt.2>&1: Redirects stderr to the same destination as stdout (nowfile.txt).- Works in all shells (Bash, sh, etc.).
Method 2: Bash-Specific Shortcut
command &>> file.txt
&>> file.txt: Appends both stdout and stderr tofile.txt.- Only works in Bash (not POSIX-compliant shells like
sh).
Example
# Append stdout and stderr to log.txt
echo "This is stdout" >> log.txt 2>&1
ls /non-existent-directory &>> log.txt
Key Notes
- Order Matters:
command >> file.txt 2>&1is correct.command 2>&1 >> file.txtdoes not work (stderr would still go to the terminal).
- File Creation:
- If
file.txtdoesn’t exist, it will be created automatically.
- Overwrite vs. Append:
- Use
>or&>to overwrite the file. - Use
>>or&>>to append to the file.
Verification
Check the contents of log.txt:
cat log.txt
Output:
This is stdout
ls: /non-existent-directory: No such file or directory
Summary
- Use
>> file.txt 2>&1for portability across shells. - Use
&>> file.txtfor conciseness in Bash.