Why Isn’t My Bash File Descriptor Closing After the First Read?

0
13
Asked By TechWhiz232 On

I've been working with a bash script where I'm trying to read from a file descriptor, but I'm confused about why it doesn't close after my first 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 file descriptor. Can anyone clarify why this happens?

3 Answers

Answered By CodeNinjaX On

The programming manual states that if `{varname}` is provided, the redirection can persist, which allows for better control over the file descriptor's lifetime without needing `exec`. You might be observing behavior based on that, but I can't verify it without having a machine to test on right now.

Answered By SkepticCoder97 On

It looks like your code formatting might be a bit tricky for some platforms. If possible, try not to use inline code blocks when posting bash code. Just add four spaces at the beginning of each line to make it clearer.

Regarding your issue, you can't close a file descriptor in the way you're attempting. You would need to explicitly execute `exec {fd}<&-` to close it. Otherwise, it just gets moved to the standard input.

Answered By BashMaster2000 On

According to the bash man page, when using `exec`, the redirections affect the file handles in the current shell session. However, if you use `mycommand {fd}<-`, it can close the file descriptor. But, if you're working with processes forked from that command, the closures might not behave as you expect. The confusion often arises with builtin commands like `read` that don't follow the same rules as external commands.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.