I've been working on a bash program where I expect the file descriptor to close after a read command. Here's the code I'm using:
```bash
printf "This is the first linernThis is the second linern" > "test.txt"
: {fd}< "test.txt"
read <&$fd-
printf "$?; $REPLYn"
read &digit-` should close the digit after duplicating it to n, but that doesn't seem to be the case here. I'm a bit confused about the behavior, and I'd appreciate any insights on this!
3 Answers
The nature of redirections means they only apply to specific commands unless you modify the actual shell environment with `exec`. That’s why your `read <&$fd-` command closes the fd for that specific read command, but `$fd` remains open in your shell afterward. Test it out, you'll see it works as expected!
It is! But now it’s starting to clear up after hearing all your explanations.
It looks like you're trying to close a file descriptor with your method, but it won't work like that. You need to explicitly close it using `exec {fd}<&-`. This approach helps avoid any ambiguity with file descriptors in your script.
Just to clarify, are you saying that the `read` command won't close the fd? Seems a bit counterintuitive, right?
Exactly! I didn't expect that either, especially based on what the manual states.
Check this out from the bash manual: if you use `{varname}<&-` with exec, it stays open across the command's scope. However, when you do the `read <&$fd-`, it transfers the file descriptor for just that command, which is likely why it's still open after. The redirection needs to be done carefully to manage file descriptors properly.
That makes sense now! So it's all about how the scope works within bash, huh?
Yeah, exactly! Just figured that part out, thanks!

I appreciate that! I thought it was weird that it seemed inconsistent!