bashfile-io

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


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 Bash always requires you to specify the number, e.g. like this:

exec 3< /path/to/a/file    # Open file for reading on file descriptor 3.

In contrast, I would like to be able to do something like

my_file_descriptor=$(open_r /path/to/a/file)

which would open 'file' for reading on the lowest-numbered file descriptor not yet in use and assign that number to the variable 'my_file_descriptor'.


Solution

  • 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 other 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 bash 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