Linux 中每個進程預設開啟三個檔案描述符:
重定向即改變這些描述符指向的目標(檔案、裝置或另一程式)。
| 語法 | 說明 | 範例 |
|---|---|---|
cmd > file | 標準輸出導向檔案(覆蓋) | ls -l > list.txt |
cmd >> file | 標準輸出追加到檔案 | echo "new line" >> log.txt |
cmd 1> file | 同 cmd > file(明確指定 fd 1) | find / -name "*.conf" 1> result.txt |
cmd 2> file | 標準錯誤導向檔案(覆蓋) | gcc test.c 2> error.log |
cmd 2>> file | 標準錯誤追加到檔案 | make 2>> build.err |
cmd > file 2>&1 | stdout 與 stderr 合併導向檔案(覆蓋) | ./run.sh > all.log 2>&1 |
cmd >> file 2>&1 | stdout 與 stderr 合併追加 | ./daemon.sh >> daemon.log 2>&1 |
cmd &> file | Bash 簡寫:合併 stdout/stderr 覆蓋 | python3 script.py &> output.txt |
cmd &>> file | Bash 簡寫:合併追加 | ./test &>> test.log |
| 語法 | 說明 | 範例 |
|---|---|---|
cmd < file | 從檔案讀取標準輸入 | sort < unsorted.txt |
cmd << EOF ... EOF | Here Document:從標準輸入讀取直到分隔符 | cat << EOF > file.txt |
cmd <<< "string" | Here String:直接提供字串作為輸入 | tr a-z A-Z <<< "hello" |
# 將 fd 3 指向檔案
exec 3> output.txt
echo "test" >&3
exec 3>&- # 關閉 fd 3
# 交換 stdout 與 stderr
cmd 3>&1 1>&2 2>&3
./build.sh 2>&1 | tee build.log
命令>! 文件:!csh 強制覆蓋語法,Bash 不支援,請用 >| 或直接 >(若設定 set -o noclobber)。命令>& 文件:csh 語法,Bash 請用 &> 或 > file 2>&1。command filename2:原文殘缺,應為 cmd < file1 > file2。1> 2> 增加可讀性。logrotate 管理日誌檔案大小。Linux 系統啟動流程深度解析:從 BIOS 到登入 Shell
Linux VPS 安全加固實戰:從帳號管理、SSH 防護到防火牆策略全攻略
Linux 修改鍵盤映射:將 CapsLock 重映射為 Ctrl 鍵 (xmodmap 方案)
VMware Server 在 Linux 與 Windows 下的安裝、配置與常見問題排查
CentOS 5.6 安裝小小輸入法 (yong) 遇坑記:狀態欄消失、無法輸入中文的排查與替代方案
Nginx 反向代理核心配置:proxy_pass 與關鍵 Header 設置詳解