[英]why the command; ls -l file_doesnot_exists > /dev/null 2>&1 is working while; ls -l 2>&1 file_doesnot_exists > /dev/null is not
我只是想知道如何知道我們通常將哪個指令放在 shell 命令中? 例如,為什么命令:
ls -l file_doesnot_exists > /dev/null 2>&1
正在工作,而此命令:
ls -l 2>&1 file_doesnot_exists > /dev/null
不是
筆記:
linux
,這意味着ls
不是PowerShell 自己的Get-ChildItem
cmdlet 的內置別名(僅適用於Windows ),而是指標准/bin/ls
Z6EC1BD1EA6A5D62BDD63B 實用程序。在PowerShell中,您的命令之間沒有區別,因為重定向的順序無關緊要。
所有目標output 流始終保留其身份: stream 的任何重定向都會影響到同一命令中相同 stream 的任何其他重定向。
Therefore, neither of your commands work as intended and produce no output , because while 2>&1
redirects the error stream ( 2
) into the success output stream ( 1
), the latter's output is ultimately discarded , due to > /dev/null
( >
與1>
相同),包括重定向的錯誤流 output。
相比之下,在與POSIX 兼容的 shell (例如 Bash )中,重定向的順序確實很重要:
ls -l 2>&1 file_doesnot_exists > /dev/null
按預期工作:
2>&1
將標准錯誤 output 重定向到原始標准輸出。>
和1>
一樣)對2>&1
沒有影響/dev/null
)。 相比之下, ls -l file_doesnot_exists > /dev/null 2>&1
DOES NOT並且不會產生output :
> /dev/null
將標准輸出重定向到/dev/null
,即有效地丟棄標准輸出 output。
因為2>&1
在命令后面出現,所以1
指的是已經重定向的標准輸出,所以標准錯誤 output 也被丟棄。
有關更多信息,請參閱此答案。
假設這是在 PowerShell 核心中運行的(因為標簽表明它是),假設您將 bash 命令與 PowerShell cmdlet 混淆是安全的。 在 PowerShell 中,您必須注意Terminating和Non- Termying 錯誤。
簡而言之, ls -l 2>&1 file_doesnot_exists > /dev/null
不起作用的原因是, ls
- Get-ChildItem
的別名- 產生一個終止錯誤,該錯誤會停止執行的 rest,因為它缺少參數. 這在Try {...} catch {...}
語句中得到了證明,其中catch
塊“捕獲”終止錯誤。
try {
ls -l
}
catch {
"it no workie"
}
由於ls
是Get-ChildItem
的別名,因此L
參數默認為-LiteralPath
,它現在需要一個路徑,並且由於未提供它而在運行時出錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.