Monday, 29 January 2018

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



To redirect stdout to a truncated file in Bash, I know to use:



cmd > file.txt


To redirect stdout in Bash, appending to a file, I know to use:



cmd >> file.txt


To redirect both stdout and stderr to a truncated file, I know to use:



cmd &> file.txt


How do I redirect both stdout and stderr appending to a file? cmd &>> file.txt did not work for me.


Answer



cmd >>file.txt 2>&1


Bash executes the redirects from left to right as follows:




  1. >>file.txt: Open file.txt in append mode and redirect stdout there.

  2. 2>&1: Redirect stderr to "where stdout is currently going". In this case, that is a file opened in append mode. In other words, the &1 reuses the file descriptor which stdout currently uses.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...