syf*_*uqs 3 bash io-redirection shell-script exec read
#!/bin/bash
echo 123456789 > out.txt
exec 3<> out.txt
read -n 4 <&3
echo -n 5 >&3
exec 3>&-
Run Code Online (Sandbox Code Playgroud)
面试笔试,被问到脚本末尾out.txt的内容。我确实运行了脚本后记,它给了我123456789. 但是我不知道脚本中发生了什么,尤其是带有 exec 语句的部分。我查找了联机帮助页和谷歌搜索结果,exec但找不到任何相关内容3<>。精通shell脚本的人可以解释这里发生了什么吗?
echo 123456789 > out.txt写入字符串123456789的out.txt文件。
该exec 3<>out.txt构造打开文件out.txt进行读写<并将>其附加到文件描述符 #3。
read -n 4 <&3 读取 4 个字符。
echo -n 5 >&3 写 5(用 5 替换 5)。
exec 3>&- 关闭文件描述符#3。
导致
cat out.txt
123456789
Run Code Online (Sandbox Code Playgroud)
关于execint 的部分bash(1)指出:
exec [-cl] [-a name] [command [arguments]]如果command指定,它将替换外壳。[...]如果command未指定,任何重定向都会在当前 shell 中生效 [...]。