Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

file-io

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'.

like image 406
Mikko Östlund Avatar asked Nov 28 '11 14:11

Mikko Östlund


People also ask

Is 0 a valid file descriptor?

0 is a valid file descriptor, but it usually refers to stdin.

What is the 0 file descriptor?

At the file descriptor level, stdin is defined to be file descriptor 0, stdout is defined to be file descriptor 1; and stderr is defined to be file descriptor 2.


1 Answers

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 
like image 121
weldabar Avatar answered Sep 28 '22 06:09

weldabar