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

后端 未结 6 1768
梦毁少年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:23

    I needed to support both bash v3 on Mac and bash v4 on Linux and the other solutions require either bash v4 or Linux, so I came up with a solution that works for both, using /dev/fd.

    find_unused_fd() {
      local max_fd=$(ulimit -n)
      local used_fds=" $(/bin/ls -1 /dev/fd | sed 's/.*\///' | tr '\012\015' '  ') "
      local i=0
      while [[ $i -lt $max_fd ]]; do
        if [[ ! $used_fds =~ " $i " ]]; then
          echo "$i"
          break
        fi
        (( i = i + 1 ))
      done
    }
    

    For example to dup stdout, you can do:

    newfd=$(find_unused_fd)
    eval "exec $newfd>&1"
    

提交回复
热议问题