目錄 一. 簡介 二. 常見用法 2.1 輸出重定向 2.2 錯誤重定向 2.3 同時重定向標準輸出 + 錯誤 2.4 輸入重定向 2.5 特殊設備 三. 這樣設計的好處 3.1 區分正常信息和錯誤信息 3.2 方便調用方腳本處理 3.3 與管道結合時更清晰 四. 案例
一. 簡介
?在 Linux/Unix 中,一切都是文件(文件、目錄、設備、管道、網絡套接字等)。 當進程打開一個文件(或設備、socket 等),內核會返回一個 整數編號 來代表它,這個編號就是 FD
。 ※File Descriptor
(文件描述符)的簡寫。
進程之后對這個文件的所有操作(讀、寫、關閉等)都是通過FD
文件描述符來完成的。
FD 名稱 說明 默認指向 0
stdin
標準輸入 鍵盤 1
stdout
標準輸出 終端屏幕 2
stderr
標準錯誤 終端屏幕
二. 常見用法
2.1 輸出重定向
寫法 含義 command > file
把 標準輸出 寫入文件,覆蓋 command >> file
把 標準輸出 追加到文件 command 1> file
等同于 > file
,指定 stdout
2.2 錯誤重定向
寫法 含義 command 2> file
把 標準錯誤 寫入文件 command 2>> file
把 標準錯誤 追加到文件 command 2>&1
把 stderr 重定向到 stdout 的位置
2.3 同時重定向標準輸出 + 錯誤
寫法 含義 command > file 2>&1
stdout 和 stderr 都寫入 file
command &> file
Bash專用簡寫 ,stdout+stderr 一起寫入 file
command &>> file
stdout+stderr 一起追加到 file
2.4 輸入重定向
寫法 含義 command < file
把文件作為標準輸入 command 0< file
等同于 < file
2.5 特殊設備
寫法 含義 >/dev/null
丟棄 stdout 2>/dev/null
丟棄 stderr &>/dev/null
丟棄 stdout + stderr(Bash常用,不兼容sh) 💥>/dev/null 2>&1
丟棄 stdout + stderr(兼容所有shell)
三. 這樣設計的好處
3.1 區分正常信息和錯誤信息
stdout
通常表示程序的正常結果(比如命令執行的輸出)。stderr
用來提示警告、錯誤、用戶輸入異常等情況。
echo "正常結果"
echo "出錯了!" > &2
3.2 方便調用方腳本處理
上層腳本或調用者可以分別捕獲 stdout 和 stderr。
./myscript.sh > output.log 2 > error.log
3.3 與管道結合時更清晰
管道|
只會傳遞 stdout
,stderr
會被分開。 如果 command1
里錯誤信息走 stderr
,它就不會影響后面的數據處理邏輯。
command1 | command2
四. 案例
4.1 if判斷
?判斷指定的環境變量是否存在
>/dev/null 2>&1
:用于將printenv USERNAME
的標準輸出和錯誤全部丟棄
if printenv USERNAME > /dev/null 2 >&1 ; then echo "環境變量 USERNAME 存在"
else echo "環境變量 USERNAME 不存在"
fi
if printenv USERNAME &> /dev/null; then echo "環境變量 USERNAME 存在"
else echo "環境變量 USERNAME 不存在"
fi
?判斷指定的命令是否存在
if ! command -v keytool > /dev/null 2 >&1 ; then echo "【keytool】命令并沒有被安裝, 請確認!" exit 1
fi
4.2 ls查詢
有2個文件夾,其中0915
的文件夾只有root用戶才能讀取其中的文件 直接ls -l 09*
查看時,會提示權限不足 2>/dev/null
將標準錯誤丟棄之后,屏幕上不會顯示錯誤提示
apluser@FengYeHong-HP:work$ ls -ld 09*
drwx------ 2 root root 4096 Sep 15 18 :58 0915
drwxr-xr-x 2 apluser apluser 4096 Sep 15 19 :00 0915_01
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ ls -l 09*
ls: cannot open directory '0915' : Permission denied
0915_01:
total 0
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ ls -l 09* 2 > /dev/null
0915_01:
total 0
ls 09* >out.txt 2>err.txt
:stdout 到 out.txt,stderr 到 err.txt
apluser@FengYeHong-HP:work$ ls 09*
ls: cannot open directory '0915' : Permission denied
0915_01:
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ ls 09* > out.txt 2 > err.txt
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ cat out.txt
0915_01:
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ cat err.txt
ls: cannot open directory '0915' : Permission denied
ls 09* >all_info.txt 2>&1
:stdout 和 stderr 都輸出到 all.txt
apluser@FengYeHong-HP:work$ ls 09* > all_info.txt 2 >&1
apluser@FengYeHong-HP:work$
apluser@FengYeHong-HP:work$ cat all_info.txt
ls: cannot open directory '0915' : Permission denied
0915_01: