einpoklum
einpoklum

Reputation: 131415

Using a new file descriptor for subsequent bash commands

I'm trying to follow the bash advanced scripting guide and use an additional (output) file descriptor. I'm running:

3>/tmp/foo
echo hello >&3

but instead of this putting "hello" in /tmp/foo, I get the error:

bash: 3: Bad file descriptor

Why is that?

Note: In case it matters, I'm using bash 4.4.

Upvotes: 1

Views: 42

Answers (1)

einpoklum
einpoklum

Reputation: 131415

It seems you have to say exec in order for the the file descriptor creation to apply to subsequent commands. So, this:

exec 3>/tmp/foo
echo hello >&3

won't give an error message. However, that's bad coding practice, as @Inian suggests. Instead, you should have bash open the smallest available new file descriptor, using the following:

exec {my_new_fd}>/tmp/foo
echo hello >&${my_new_fd}

that way you can be sure you're not trading on anybody else's file descriptors.

Upvotes: 4

Related Questions