每个进程中,shell脚本可以直接在命令行中执行,也可以将一套逻辑组织成一个文件,而stdout会在命令行中显示,stdin也会在命令行中进行输入,故我们有时可能需要使用文件中的内容进行输入输出,有了重定向命令。
每个进程默认打开3个文件描述符:
stdin
标准输入,从命令行读取数据,文件描述符为0stdout
标准输出,向命令行输出数据,文件描述符为1stderr
标准错误输出,向命令行输出数据,文件描述符为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