In Bash, how to find the lowest-numbered unused file descriptor?

后端 未结 6 1761
梦毁少年i
梦毁少年i 2021-01-30 16:45

In a Bash-script, is it possible to open a file on \"the lowest-numbered file descriptor not yet in use\"?

I have looked around for how to do this, but it seems that Bas

6条回答
  •  梦如初夏
    2021-01-30 17:17

    I know this thread is old, but believe that the best answer is missing, and would be useful to others like me who come here searching for a solution.

    Bash and Zsh have built in ways to find unused file descriptors, without having to write scripts. (I found no such thing for dash, so the above answers may still be useful.)

    Note: this finds the lowest unused file descriptor > 10, not the lowest overall.

    $ man bash /^REDIRECTION (paragraph 2)
    $ man zshmisc /^OPENING FILE DESCRIPTORS
    

    Example works with bsh and zsh.

    Open an unused file descriptor, and assign the number to $FD:

    $ exec {FD}>test.txt
    $ echo line 1 >&$FD
    $ echo line 2 >&$FD
    $ cat test.txt
    line 1
    line 2
    $ echo $FD
    10  # this number will vary
    

    Close the file descriptor when done:

    $ exec {FD}>&-
    

    The following shows that the file descriptor is now closed:

    $ echo line 3 >&$FD
    bash: $FD: Bad file descriptor
    zsh: 10: bad file descriptor
    

提交回复
热议问题