--- title: "20-文件重定向" created: 2025-11-25 tags: - 项目 aliases: - 文件重定向 --- # 文件重定向 每个进程默认打开3个文件描述符: - stdin标准输入,从命令行读取数据,文件描述符为0 - stdout标准输出,向命令行输出数据,文件描述符为1 - stderr标准错误输出,向命令行输出错误数据,文件描述符为2 可以用文件重定向将这三个文件重定向到其他文件中。 ## 重定向命令列表 | 命令 | 说明 | | --- | --- | | command > file | 将stdout重定向到file中 | | command < file | 将stdin重定向到file中 | | command >> file | 将stdout以追加方式重定向到file中 | | command n> file | 将文件描述符n重定向到file中 | | command n>> file | 将文件描述符n以追加方式重定向到file中 | ## 输入和输出重定向 ```bash echo -e "Hello \c" > output.txt # 将stdout重定向到output.txt中 echo "World" >> output.txt # 将字符串追加到output.txt中 read str < output.txt # 从output.txt中读取字符串 echo $str # 输出结果:Hello World ``` ## 同时重定向stdin和stdout 创建bash脚本: ```bash #! /bin/bash read a read b echo $(expr "$a" + "$b") ``` 创建input.txt,里面的内容为: ```text 3 4 ``` 执行命令: ```bash chmod +x test.sh # 添加可执行权限 ./test.sh < input.txt > output.txt # 从input.txt中读取内容,将输出写入output.txt中 cat output.txt # 查看output.txt中的内容 7 ``` > [!note] 为什么是 7:`3 + 4` 的求和经 stdin 进入脚本、结果经 stdout 落入 output.txt——输入输出双向重定向在一次命令里完成。 ## 常见应用示例 - `ls -l > 文件`(列表的内容写入文件a.txt中 覆盖写) - `ls -al >> 文件`(列表的内容文件追加到文件aa.txt的末尾) - `cat 文件1 > 文件2`(将文件1的内容覆盖到文件2) - `echo "内容" >> 文件`(将echo的内容追加到文件末尾) ## 标准错误重定向与黑洞设备 `>` 默认只重定向 stdout,程序报错信息走 stderr,仍然会打到屏幕。想让错误信息也进文件,需要显式写 `2>`;`2>&1` 表示"把文件描述符 2 合并到 1 当前指向的位置",`&>` 是 bash 的等价简写: ```bash ./test.sh > out.txt 2> err.txt # 正常输出与错误输出分开存放 ./test.sh > all.txt 2>&1 # 两者合并到同一个文件 ./test.sh &> all.txt # 同上,bash 简写 ``` `/dev/null` 是一个"黑洞"设备,写入的内容全部丢弃,常用来静默不需要的输出: ```bash command > /dev/null 2>&1 # 丢弃全部输出,只关心命令是否执行成功($?) ``` > [!tip] 判断重定向写法的小口诀 > 箭头左边写数字就是针对那个文件描述符:`1>` 即 `>`(可省略 1),`2>` 针对 stderr;`>>` 是追加版。`n>&m` 是"复制"而非"指向同一个文件名"——它让 n 指向 m 当前已经打开的那个文件,因此 `2>&1` 必须写在 `> all.txt` **之后**,写反了 stderr 会跟着重定向前的屏幕走。 --- **项目分区导航**:[[19-exit命令|exit命令]] ⬅️ | 20-文件重定向 | ➡️ [[21-导入外部脚本|导入外部脚本]]