1

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 1
    You shouldn't be arbitrarily picking up file descriptors of choice and start using it. You can let the shell find the next available one, see this answer - https://stackoverflow.com/a/41620630/5291015 – Inian Nov 08 '20 at 11:48
  • 1
    And please don't use tdlp.org. It is archaic, and not does not conform to latest and recommended bash standards. Use the official documentation or Greg's wiki at https://mywiki.wooledge.org/BashGuide – Inian Nov 08 '20 at 11:49
  • @Inian: Point taken; see also the edit to my answer. – einpoklum Nov 08 '20 at 14:18

1 Answers1

4

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684