簡體   English   中英

為什么要命令; ls -l file_doesnot_exists > /dev/null 2>&1 正在工作; ls -l 2>&1 file_doesnot_exists > /dev/null 不是

[英]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 重定向到原始標准輸出。
      • 后面的 stdout 重定向( >1>一樣)對2>&1沒有影響
      • 最終效果是只有stderr行打印到 stdout,而 stdout 行被丟棄(通過重定向到/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 中,您必須注意TerminatingNon- Termying 錯誤。

簡而言之, ls -l 2>&1 file_doesnot_exists > /dev/null不起作用的原因是, ls - Get-ChildItem的別名- 產生一個終止錯誤,該錯誤會停止執行的 rest,因為它缺少參數. 這在Try {...} catch {...}語句中得到了證明,其中catch塊“捕獲”終止錯誤。

try {
    ls -l
}
catch {
    "it no workie"
}

由於lsGet-ChildItem的別名,因此L參數默認為-LiteralPath ,它現在需要一個路徑,並且由於未提供它而在運行時出錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM