Ubuntu – In what order does the shell execute commands and stream redirection

bashcommand lineredirect

I was trying to redirect both stdout and stderr to a file today, and I came across this:

<command> > file.txt 2>&1

This apparently redirects stderr to stdout first, and then the resulting stdout is redirected to file.txt.

However, why isn't the order <command> 2>&1 > file.txt? One would naturally read this as (assuming execution from left to right) the command being executed first, the stderr being redirected to stdout and then, the resulting stdout being written to file.txt. But the above only redirects stderr to the screen.

How does the shell interpret both the commands?

Best Answer

When you run <command> 2>&1 > file.txt stderr is redirected by 2>&1 to where stdout currently goes, your terminal. After that, stdout is redirected to the file by >, but stderr is not redirected with it, so stays as terminal output.

With <command> > file.txt 2>&1 stdout is first redirected to the file by >, then 2>&1 redirects stderr to where stdout is going, which is the file.

It may seem counter intuitive to start with, but when you think of the redirections in this way, and remember that they are processed from left to right it makes much more sense.

Related Question