How to find next available file descriptor in Bash?

前端 未结 5 2129
离开以前
离开以前 2020-12-15 11:40

How can I figure out if a file descriptor is currently in use in Bash? For example, if I have a script that reads, writes, and closes fd 3, e.g.

exec 3<          


        
5条回答
  •  遥遥无期
    2020-12-15 12:15

    If you do not care if the file descriptor is above 9, you may ask the shell itself to provide one. Of course, the fd is guaranteed to be free by the own shell.

    Feature available since bash 4.1+ (2009-12-31) {varname} style automatic file descriptor allocation

    $ exec {var}>hellofile
    $ echo "$var"
    15
    
    $ echo "this is a test" >&${var}
    $ cat hellofile
    this is a test
    
    $ exec {var}>&-                      # to close the fd.
    

    In fact, in linux, you can see the open fds with:

    $ ls /proc/$$/fd
    0 1 2 255
    

提交回复
热议问题