创建输入文件描述符

创建输入文件描述符

Content #

在重定向到文件之前,先将STDIN指向的位置保存到另一个文件描述符,然后在读取完文件之后将STDIN恢复到原先的位置:

$ cat test15
#!/bin/bash
# redirecting input file descriptors

exec 6<&0

exec 0< testfile

count=1
while read line
do
   echo "Line #$count: $line"
   count=$[ $count + 1 ]
done
exec 0<&6
read -p "Are you done now? " answer
case $answer in
Y|y) echo "Goodbye";;
N|n) echo "Sorry, this is the end.";;
esac
$ ./test15
Line #1: This is the first line.
Line #2: This is the second line.
Line #3: This is the third line.
Are you done now? y
Goodbye
$

在这个例子中,文件描述符6用于保存STDIN指向的位置。然后脚本将STDIN重定向到一个文件。read命令的所有输入都来自重定向后的STDIN(也就是输入文件)。

在读完所有行之后,脚本会将STDIN重定向到文件描述符6,恢复STDIN原先的位置。该脚本使用另一个read命令来测试STDIN是否恢复原位,这次read会等待键盘的输入。

From #

Linux命令行与shell脚本编程大全