Linux bash 中,如何將正常信息和錯誤信息輸出到文件


 

問題描述:

$ command 2>> error

$ command 1>> output

是否有方法,在bash同一行,實現輸出stderr到error文件,輸出stdout到output文件?

也就是,如何在bash的同一行,實現stderr和stdout重定向到不同的文件?

 

解決方法:

將它們放入同一行,command 2>> error 1>> output

然而,注意 >> 是如果文件有數據,會在文件尾部添加內容。而 > 將會重寫文件中已經存在的數據。

只是為了完成目的,你可以寫 1> 為 > , 因為其默認的文件描述符是輸出。所以1> 和 > 是同樣的東西。

所以,

command 2> error 1> output 成為 command 2> error > output

command 2>> error 1>> output 成為 command 2>> error >> output

 

或者如果你想要把輸出(stdout & stderr)混合到同一個文件,可以使用命令:

command > merged-output.txt 2>&1

更簡單的用法:command &> merged-output.txt

其中

2>&1 表示 stderr(文件描述為2) 重定位到stdout(文件描述符為1),也就是標准錯誤信息發送到與標准輸出信息的相同位置。

 

補充說明:

在bash中,0, 1, 2...9 是文件描述符。0代表stdin,1代表stdout,2代表stderror。3~9未使用,可用於其他臨時用法。

任何文件描述符能通過使用操作符符 > 或 >>(append) ,重定向為其他文件描述符或文件。

用法:<file_descriptor> > <filename | &file_descriptor>

更多內容,請參考

http://www.tldp.org/LDP/abs/html/io-redirection.html

 

技巧:

Linux make時,可能會出現很多調試信息,若出現錯誤,由於輸出信息過多,在bash下,無法查找到第一個出錯的位置的錯誤信息。此時,就可以采取上面的方法,先將其輸出到文件,然后,在文件中,查找第一個出錯信息的位置。

 

參考資料:

1、How to redirect stderr and stdout to different files in the same line of bash?

http://stackoverflow.com/questions/7901517/how-to-redirect-stderr-and-stdout-to-different-files-in-the-same-line-of-bash


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM