「Linux文件及目录管理」输入输出重定向与管道
知识点解析
输入/输出重定向
- 标准输入(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
末尾。>
会清空目标文件后写入,>>
会保留原有内容并在末尾追加。
案例:重定向标准错误
# 查看当前目录下的内容