鍊式重定向的內部邏輯

鍊式重定向的內部邏輯

當我打字時

cat some_file > new_file1 > new_file2

some_file我從innew_file2和 empty得到輸出new_file1

這其中的內在邏輯是什麼?更具體地說,stdout文件的內容是什麼?

注意:在 Windows 上,會跳過中間檔案。

答案1

這取決於外殼。

在 bash 中,echo derp >file1 >file2首先打開file1,截斷它,然後安排將stdoutofecho derp寫入file1。然後 bash 對 執行相同的操作file2:它打開file2、截斷它,並安排將stdoutofecho derp寫入而不是寫入file2

最終效果是被file1截斷(即內容被刪除)並且stdout僅進入file2.沒有發生連結。 Bash 一次只能將標準輸出重新導向到一個地方。對於管道也是如此:echo derp > file | cat“derp”的結果被寫入文件,而不是管道。

然而,在 zsh 中,正如您直觀所期望的那樣,echo derp >file1 >file2同時寫入file1和。如果您使用 zsh,file2請參閱 MULTIOS以了解詳細資訊。man zshmisc

要在 之外實現此目的zsh,您可以簡單地使用tee:echo derp | tee file1 file2 > /dev/null相當於 zsh 的echo derp >file1 >file2

相關內容