简体   繁体   English

理解大括号对重定向的影响 ("> file1 >& file2" vs. "{ > file1; } >& file2")

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

Please consider the following bash script:请考虑以下 bash 脚本:

#!/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?有人可以解释为什么由倒数第二行中的重定向导致的错误消息没有被尾随&>/dev/null抑制,而它在最后一行中按预期工作?

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.我研究了 bash 手册中有关重定向和复合命令的段落(特别是有关组命令的部分),但无法从中做出解释。 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?差异是否与 bash 解析行的顺序有关?

According to bash manual ( man bash ):根据 bash 手册( 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.对于> temp >& /dev/null ,当 bash 处理> temp部分时,stderr 仍然指向 tty,因此您可以看到错误。 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 { > temp; } &> /dev/null , the { > temp; } { > temp; } &> /dev/null , { > temp; } { > temp; } is handled as a compound command and its output as a whole is redirected by &> /dev/null . { > temp; }作为复合命令处理,其输出作为一个整体由&> /dev/null重定向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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