环境: GNU bash,版本 3.2.57(1)-release (x86_64-apple-darwin20)
尝试0:
exec 3<> "$(mktemp)" # open file descriptor 3 to a temp file for read/write
echo 'foo' >&3 # write 'foo' to descriptor 3
read bar <&3 # read contents of descriptor 3 to variable named bar (not using -u 3)
echo $? # exit status returns "1"
exec 3>&- # close file descriptor 3
在上面的代码片段中,我希望$bar
设置为"foo"
但它不起作用,因为文件描述符 3 中的位置位于文件描述符文件的末尾。
尝试1:
exec 3<> "$(mktemp)" # open file descriptor 3 to a temp file for read/write
echo 'foo' >&3 # write 'foo' to descriptor 3
cat <&3 # echo contents of of descriptor 3 to STDOUT
echo $? # exit status returns "0"
exec 3>&- # close file descriptor 3
这也失败了,因为描述符 3 中的文件位置位于末尾。
在 C/C++ 中,您可以rewind(...) 和 fseek(...)将创建的文件临时文件的文件指针重置到文件mktemp
的开头。
此处已知的解决方法:(使用第二个描述符)
myTempFile="$(mktemp)" # create temp file and assign to $myTempFile
exec 3> "$myTempFile" # open file descriptor 3 for writing to $myTempFile
exec 4< "$myTempFile" # open file descriptor 4 for reading of $myTempFile
echo 'foo' >&3 # write 'foo' to descriptor 3
read bar <&4 # read contents of descriptor 4 to variable named bar
echo $? # exit status returns "0"
echo "$bar" # echo "foo"
exec 3>&- # close file descriptor 3
exec 4>&- # close file descriptor 4
问题™(最终):
如何在 bash 中回退文件描述符而不使用第二个文件描述符从头开始读取?
注意:我不想安装ksh93来使用它的倒带功能。
exec 3<> "$(mktemp)"
echo 'foo' >&3
# Magic Happens here
read bar <&3 # expect $bar == "foo"
echo $? # expect "0"
exec 3>&-