Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

    cat < foo 2>bar
    bash : cannot open foo : No such file or directory
share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

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
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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