简体   繁体   中英

Understanding the effect of curly braces with respect to redirections ("> file1 >& file2" vs. "{ > file1; } >& file2")

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?

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 { > temp; } &> /dev/null , the { > temp; } { > temp; } is handled as a compound command and its output as a whole is redirected by &> /dev/null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM