Linux 脚本文件操作与输出处理技巧
1. 关闭文件描述符
在脚本中,若创建了新的输入或输出文件描述符,脚本退出时,Shell 会自动关闭它们。但有时,在脚本结束前需手动关闭文件描述符。关闭文件描述符,可将其重定向到特殊符号 &- 。示例如下:
exec 3>&-
此语句关闭了文件描述符 3,使其在脚本中无法再被使用。若尝试使用已关闭的文件描述符,会出现错误:
$ cat badtest
#!/bin/bash
# testing closing file descriptors
exec 3> test17file
echo "This is a test line of data" >&3
exec 3>&-
echo "This won't work" >&3
$ ./badtest
./badtest: 3: Bad file descriptor
$
关闭文件描述符后,向其写入数据会使 Shell 产生错误信息。另外,关闭文件描述符后若重新打开同一输出文件,Shell 会用新文件替换现有文件,导致原有内容被覆盖。示例如下:
$ cat test17
#!/bin/bash
# testing closing file descriptors
exec 3> test17file
echo "Thi
超级会员免费看
订阅专栏 解锁全文
3750

被折叠的 条评论
为什么被折叠?



