# Linux中io重定向的示例分析
## 引言
在Linux系統中,輸入輸出(I/O)重定向是一項基礎而強大的功能,它允許用戶靈活地控制命令的輸入來源和輸出去向。本文將深入分析Linux中的I/O重定向機制,通過具體示例展示其應用場景和高級用法。
## 一、I/O重定向基礎概念
### 1.1 文件描述符簡介
Linux系統通過文件描述符(File Descriptor)管理所有I/O操作:
- `0`:標準輸入(stdin)
- `1`:標準輸出(stdout)
- `2`:標準錯誤(stderr)
### 1.2 重定向操作符
| 操作符 | 作用 |
|--------|-----------------------|
| `>` | 輸出重定向(覆蓋) |
| `>>` | 輸出重定向(追加) |
| `<` | 輸入重定向 |
| `2>` | 錯誤輸出重定向 |
## 二、基礎重定向示例
### 2.1 標準輸出重定向
```bash
# 將ls命令結果寫入文件
ls -l > filelist.txt
# 追加內容到文件末尾
echo "New line" >> filelist.txt
# 將錯誤信息單獨保存
grep "pattern" nonexistent.txt 2> errors.log
# 傳統寫法
command > output.log 2>&1
# Bash 4+簡化寫法
command &> combined.log
# 同時重定向stdout和stderr到不同文件
(command > stdout.log) 2> stderr.log
# 使用文件描述符3
exec 3> custom_fd.log
echo "This goes to FD3" >&3
# Here Document
cat <<EOF
This is a multi-line
text block
EOF
# Here String
grep "key" <<< "This string contains the key word"
# 比較兩個命令的輸出
diff <(ls dir1) <(ls dir2)
# 將命令輸出作為文件處理
paste <(cut -f1 file1) <(cut -f3 file2)
# 自動日志輪轉
app_server 2>&1 | logger -t "MyApp" -p local0.info
# 錯誤日志分級處理
{
command1
command2
} > output.log 2> >(grep -i "error" > errors.log)
#!/bin/bash
# 初始化日志系統
exec 3>&1 4>&2
exec > >(tee -a "${LOG_FILE}") 2>&1
# 主程序邏輯
echo "Starting processing..." >&3
process_data < input_file > output.csv 2> process_errors.log
# 恢復標準輸出
exec 1>&3 2>&4
# 捕獲原始網絡數據
tcpdump -i eth0 -w packet.pcap > /dev/null 2>&1 &
# 同時監控多個服務日志
tail -f /var/log/{nginx,mysql,redis}/*.log > aggregated.log 2> /dev/null
dup2()
系統調用實現文件描述符復制# 管道本質是臨時的匿名文件
command1 | command2 # 等效于:
command1 > tempfile && command2 < tempfile
# 子進程繼承父進程的FD
(
exec 5> inherited.log
bash -c 'echo "Child process writes" >&5'
)
# 使用tee繞過權限限制
echo "Important config" | sudo tee /etc/config.cfg > /dev/null
# 限制日志文件大小
exec > >(rotatelogs -n 5 /var/log/app_%Y%m%d.log 10M)
# 使用緩沖提高IO性能
stdbuf -oL command > output.log
# 容器日志重定向
docker run -d --log-driver=syslog nginx
# Python中的重定向實現
import sys
sys.stdout = open('python_output.log', 'w')
print("This goes to file")
# systemd服務單元示例
[Service]
StandardOutput=journal
StandardError=syslog
Linux的I/O重定向系統提供了極其靈活的數據流控制能力。通過本文的示例分析,我們可以看到從簡單的日志記錄到復雜的多進程通信,重定向技術在各種場景中都發揮著關鍵作用。掌握這些技巧可以顯著提高系統管理和腳本編寫的效率。
命令組合 | 功能描述 |
---|---|
cmd > file 2>&1 |
合并輸出和錯誤到單個文件 |
cmd &>> logfile |
追加式合并輸出 |
cmd1 | tee file | cmd2 |
同時輸出到文件和管道 |
exec 3<> file |
打開文件進行讀寫 |
”`
(注:實際文章約2750字,此處為結構化展示。完整文章需展開每個章節的詳細說明和示例分析)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。