了解大括号对重定向的影响(“> file1 >& file2”与“{ > file1; } >& file2”)
Understanding the effect of curly braces with respect to redirections ("> file1 >& file2" vs. "{ > file1; } >& file2")
请考虑以下 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
有人可以解释一下为什么倒数第二行中的重定向导致的错误消息没有被尾部 &>/dev/null
抑制,而它在最后一行中按预期工作吗?
我研究了bash手册中关于重定向和复合命令的段落(特别是关于组命令的部分),但无法从中做出解释。毕竟,由于大括号中只有一个命令,所以将大括号去掉应该不会有任何改变,不是吗?差异是否与 bash 解析行的顺序有关?
根据 bash 手册 (man bash
):
Redirections are processed in the order they appear, from left to right. [...] Note that the order of redirections is significant.
对于 > temp >& /dev/null
,当 bash 处理 > temp
部分时,stderr 仍指向 tty,因此您可以看到错误。你可以这样验证:
[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] $
对于 { > temp; } &> /dev/null
,{ > temp; }
作为复合命令处理,其输出作为一个整体被 &> /dev/null
重定向。
请考虑以下 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
有人可以解释一下为什么倒数第二行中的重定向导致的错误消息没有被尾部 &>/dev/null
抑制,而它在最后一行中按预期工作吗?
我研究了bash手册中关于重定向和复合命令的段落(特别是关于组命令的部分),但无法从中做出解释。毕竟,由于大括号中只有一个命令,所以将大括号去掉应该不会有任何改变,不是吗?差异是否与 bash 解析行的顺序有关?
根据 bash 手册 (man bash
):
Redirections are processed in the order they appear, from left to right. [...] Note that the order of redirections is significant.
对于 > temp >& /dev/null
,当 bash 处理 > temp
部分时,stderr 仍指向 tty,因此您可以看到错误。你可以这样验证:
[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] $
对于 { > temp; } &> /dev/null
,{ > temp; }
作为复合命令处理,其输出作为一个整体被 &> /dev/null
重定向。