知識點解析
輸入/輸出重定向
- 標準輸入(stdin):默認從鍵盤讀取,文件描述符為
0
。 - 標準輸出(stdout):默認輸出到終端,文件描述符為
1
。 - 標準錯誤(stderr):默認輸出到終端,文件描述符為
2
。 - 重定向符號:
>
:覆蓋輸出到文件(如command > file
)。>>
:追加輸出到文件(如command >> file
)。<
:從文件讀取輸入(如command < file
)。2>
:重定向錯誤輸出(如command 2> error.log
)。&>
:重定向所有輸出(標準輸出+錯誤輸出)到文件(如command &> all.log
)。
管道(|
)
- 將前一個命令的輸出作為后一個命令的輸入。
- 示例:
command1 | command2
。
案例代碼與解析
案例:重定向標準輸出到文件
- 將ls命令的輸出保存到文件(test.txt)
- 將當前時間追加到文件(test.txt)
# 將ls命令的輸出保存到目錄列表文件
ls -l > test.txt
# 查看test.txt寫入的內容
cat test.txt
# 總用量 4
# -rw-------. 1 root root 1228 8月 26 2021 anaconda-ks.cfg
# -rw-r--r-- 1 root root 0 6月 21 17:17 test.txt
# 將當前時間追加到日志文件
date >> test.txt
cat test.txt
# 總用量 4
# -rw-------. 1 root root 1228 8月 26 2021 anaconda-ks.cfg
# -rw-r--r-- 1 root root 0 6月 21 17:17 test.txt
# 2025年 06月 21日 星期六 17:18:14 CST
解析:
ls -l
的輸出被覆蓋寫入test.txt
(若文件不存在則創建)。date
的輸出被追加到test.txt
末尾。>
會清空目標文件后寫入,>>
會保留原有內容并在末尾追加。
案例:重定向標準錯誤
# 查看當前目錄下的內容