您的位置:首页 > 运维架构 > Shell

shell脚本之exec操作文件描述符 + 示例

2016-03-29 15:02 387 查看
关于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>&-

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell Linux exec