Linux 標準文件描述符:
文件描述符 縮寫 描述
0 STDIN 標準輸入
1 STDOUT 標準輸出
2 STDERR 標準錯誤
標準輸入與標準輸出,指的就是鍵盤與螢幕。
當文件描述符(0、1、2)與重定向符號(<)組合之後,就能重新定向輸入、輸出及錯誤。
- command 2>file1
- 命令執行的錯誤資訊被保存到 file1 中,螢幕只顯示正確資訊。
- command 1>file1 2>file2
- 命令執行後沒有任何顯示,因為正確輸出導向 file1,錯誤導向 file2。
- command &>file1
在 shell 腳本中,可以把「錯誤」輸出導向 STDERR 指定的檔案,需要在重定向符與文件描述符之間加一個 and 符(&):
- cat test
- #!/bin/bash
- echo " this is ERROR ">&2
- echo "this is output"
- $
運行腳本:
- [root@localhost ~]#./test 2>file1
- thisis output
- [root@localhost ~]# cat file1
- thisis ERROR
也可以在腳本中使用 exec 命令:
- exec1>file1
- exec2>file2
- echo " this is ERROR ">&2
- echo "this is output"
運行如上腳本,輸出便都進入了 file1 與 file2。
同樣地,也能用 exec 0<file1 從 file1 中讀取輸入。