Environment: GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin20)
Try 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
In the above snippet I'm expecting $bar
to be set to "foo"
but it does not work because the position in the file descriptor 3 is at the end of the file descriptors file.
Try 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
This also fails because the file location in descriptor 3 is at the end.
In C/C++ you can rewind(...) and fseek(...) to reset the file pointer of the file temp file created by mktemp
to the beginning of the file.
Known workaround from here: (use second descriptor)
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
The Question™ (finally):
How do you rewind a file descriptor in bash without using a second file descriptor to read from the beginning?
NOTE: I do not want to install ksh93 to use its rewind feature.
exec 3<> "$(mktemp)"
echo 'foo' >&3
# Magic Happens here
read bar <&3 # expect $bar == "foo"
echo $? # expect "0"
exec 3>&-