文件描述符0:标准输入
文件描述符1:标准输出
文件描述符2:标准错误
文件描述符 3-9 可供用户使用。
示例一:
假设一个文本文件 name.txt 内容如下:
脚本内容如下:#!/bin/bash
#file_exec
exec 0<name.txt
read line1
read line2
read line3
read line4
read line5
read line6
read line7
echo $line1
echo $line2
echo $line3
echo $line4
echo $line5
echo $line6
echo $line7
执行脚本后输出如下:[beyes@localhost shell]$ ./file_exec.sh
root
beyes
love
duoduo 在上面的脚本中,执行了 exec 0<name.txt 后,标准输入源重定向到 name.txt。当执行 read 语句时,从 name.txt 中读取内容到变量中;而当 name.txt 中的数据不能够填满所有的变量时,剩下的变量读入为空,于是在输出时是输出空行。
如果在脚本中重定向许多数据,那么重定向每个 echo 语句时就显得很不方便。这种情况下,可以使用 exec 通知 shell 在脚本执行期间重定向特定的文件描述符:
[Bash shell] 纯文本查看 复制代码 #!/bin/sh
exec 1>testout.txt
echo "test line 1"
echo "test line 2"
echo "test line 3"
运行后,echo 出的消息都被重定向到 testout.txt 文件中:
[root@centos shell]# cat testout.txt
test line 1
test line 2
test line 3 |