本文最后更新于 283 天前,其中的信息可能已经有所发展或是发生改变。
每个进程默认打开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中 |
输入和输出重定向
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脚本:
#! /bin/bash
read a
read b
echo $(expr "$a" + "$b")
创建input.txt,里面的内容为:
3
4
执行命令:
acs@9e0ebfcd82d7:~$ chmod +x test.sh # 添加可执行权限
acs@9e0ebfcd82d7:~$ ./test.sh < input.txt > output.txt # 从input.txt中读取内容,将输出写入output.txt中
acs@9e0ebfcd82d7:~$ cat output.txt # 查看output.txt中的内容
7