bash – Understanding the Order of Redirections

bashcommand linefile-descriptorsio-redirectionshell

I don't quite understand how the computer reads this command.

cat file1 file2 1> file.txt 2>&1

If I understand, 2>&1 simply redirect Standard Error to Standard Output.

By that logic, the command reads to me as follows:

  1. concatenate files file1 and file2.

  2. send stdout from this operation to file.txt.

  3. send stderr to stdout.

  4. end?

I'm not sure what the computer's doing. By my logic, the command should be

cat file1 file2 2>&1 > file.txt

but this is not correct.

Best Answer

I find it easier to think of using assignments.

  • > is like =
  • & is like $

You start out with

1 = /dev/tty
2 = /dev/tty

then your first example, 1> file.txt 2>&1, does

1 = file.txt
2 = $1           # and currently $1 = file.txt

leaving you with

1 = file.txt
2 = file.txt

If you did it the other way, again you start with

1 = /dev/tty
2 = /dev/tty

then 2>&1 > file.txt does

2 = $1           # and currently $1 = /dev/tty
1 = file.txt

so the end result is

1 = file.txt
2 = /dev/tty

and you've only redirected stdout, not stderr.

Related Question