Reputation: 4405
Please consider the following bash script:
#!/bin/bash
touch ./temp
set -C
>./temp &>/dev/null # Visible error message output ("./test7: line 7: ./temp: cannot overwrite existing file")
{ >./temp; } &>/dev/null # No error message
Could somebody please explain why the error message which results from the redirection in the next-to-last line is not suppressed by the trailing &>/dev/null
, while it works as expected in the last line?
I have studied the paragraphs about redirection and compound commands (notably, the section about group commands) in bash's manual, but couldn't make an explanation out of it. After all, since there is only one command in the curly braces, leaving the braces away shouldn't change anything, should it? Does the difference have to do something with the order in which bash parses lines?
Upvotes: 3
Views: 433
Reputation: 20698
According to bash manual (man bash
):
Redirections are processed in the order they appear, from left to right. [...] Note that the order of redirections is significant.
For > temp >& /dev/null
, when bash handles the > temp
part, stderr is still pointing to the tty so you can see the error. You can verify like this:
[STEP 101] $ set -C
[STEP 102] $ date >> temp
[STEP 103] $
[STEP 104] $ > temp
bash: temp: cannot overwrite existing file
[STEP 105] $ > temp >& /dev/null
bash: temp: cannot overwrite existing file
[STEP 106] $
[STEP 107] $ >& /dev/null > temp
[STEP 108] $ 2> /dev/null > temp
[STEP 109] $
For { > temp; } &> /dev/null
, the { > temp; }
is handled as a compound command and its output as a whole is redirected by &> /dev/null
.
Upvotes: 5