关于exec操作文件描述符主要注意事项:
1、exec 3</home/shell/testdir/a.txt //以“只读方式”打开/home/shell/testdir/a.txt,文件描述符对应为3
2、exec 3>/home/shell/testdir/a.txt //以“只写方式”打开/home/shell/testdir/a.txt,文件描述符对应为3
3、exec 3<>/home/shell/testdir/a.txt //以“读写方式”打开/home/shell/testdir/a.txt,文件描述符对应为3
4、exec 3<&- //关闭文件描述符3
简单示例,实现功能是从a.txt文件中提取第2,4,6行的内容打印到终端并且存储到b.txt文件中,代码如下所示:
#!/bin/bash
file="/home/shell/testdir/a.txt"exec 3>/home/shell/testdir/b.txt
for N in 2 4 6;do
line=`head -$N $file | tail -1`
echo $line
echo "$line" >&3
done
echo 3>&-
运行结果: