How to redirect and append both standard output and standard error to a file with Bash ?

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 to file.txt.
  • 2>&1: Redirects stderr to the same destination as stdout (now file.txt).
  • Works in all shells (Bash, sh, etc.).

Method 2: Bash-Specific Shortcut

command &>> file.txt
  • &>> file.txt: Appends both stdout and stderr to file.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

  1. Order Matters:
  • command >> file.txt 2>&1 is correct.
  • command 2>&1 >> file.txt does not work (stderr would still go to the terminal).
  1. File Creation:
  • If file.txt doesn’t exist, it will be created automatically.
  1. 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>&1 for portability across shells.
  • Use &>> file.txt for conciseness in Bash.

Leave a Reply

Your email address will not be published. Required fields are marked *