linux – Redirecting output stream and error stream to end of file

Question:

You can redirect the output stream and (or) errors to a file with its overwriting:
1>file will output data from the output stream to a file with its creation or overwriting
2>file will output data from the error stream to a file with its creation or overwriting
1&>file (and several other options) will output data from both the output stream and the error stream to a file, creating it and overwriting it.

You can output an output stream or an error stream to a file by writing to the end of it:

1>>file 2>>file  

But if you try to do something like 1&>>file , then a syntax error will pop up.

How can I write to the end of a file from both the output stream and the error stream?

Answer:

For example in Bash like this:

$ { echo "stdout text"; echo "stderr text">&2; } >> file 2>&1
$ cat file
stdout text
stderr text

Bash redirects from left to right:

  1. >>file : opens file in pre-write mode and redirects standard output ( stdout ) there
  2. 2>&1 : redirects error output ( stderr ) to where standard output is currently being output, i.e. to the previously opened file file .

cmd 2>&1 >> file will only redirect stdout to file, since error output will be redirected to stdout before it is redirected to file:

$ { echo "stdout text"; echo "stderr text">&2; } 2>&1 >> file
stderr text
$ cat file
stdout text
Scroll to Top