Why does this command show error message despite using 2> symbol?

    cat < foo 2>bar
    bash : cannot open foo : No such file or directory

The 2> is redirecting the standard error of cat. cat is not being run however, because bash cannot open the file you specified as standard input to cat. To get the behavior you want, use

(cat < foo) 2> bar

This will run cat < foo in a subshell and redirect the error output of bash to bar. If you also want the error output from cat, you could do

(cat < foo 2> bar) 2> bar2

As @Casey notes, putting the command in a subshell works:

$ ( cat <foo ) 2>bar

However, the subshell is not necessary. A simple list works just as well:

$ { cat <foo ; } 2>bar

You don't even need the list if you observe that the order in which redirects are done makes a difference:

$ cat <foo 2>bar
bash: foo: No such file or directory
$ cat 2>bar <foo

My conclusion is that what matters is bash's processing order: the issue is whether stderr has been redirected before or after the moment when bash discovers that the redirect of stdin fails. Thus, there is no output from the last example above because bash first redirects stderr and then tries to open foo for stdin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.