'Behavior of using a combination of Input and Error redirection in UNIX

I am new to UNIX scripting and learning about input, output, and error redirection in UNIX.

I understand that there is no restriction/dependency in the sequence of using the different types of redirection.

e.g. cat < foo > bar is the same as> bar cat < foo

However, when I use the combination with an error redirection, I find that there is a dependency on the sequence of the redirection.

In my case, the file foo1 does not exist So if I run cat < foo1 2> bar, I get the error message output on the terminal

-bash: foo1: No such file or directory

Based on what I have understood, I expect the error message to be copied to the bar file.

However, when I run 2>bar cat < foo1, the error message is copied to the bar file.

So my question is: Does the sequence of redirection matter, when we are using combination of different types of redirection?

Why is the behavior different when I use error redirection, compared to input and output redirection?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source