How to find next available file descriptor in Bash?

前端 未结 5 2139
离开以前
离开以前 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:07

    The other answer that uses pre-bash-4.1 syntax does a lot unnecessary subshell spawning and redundant checks. It also has an arbitrary cut-off for the maximum FD number.

    The following code should do the trick with no subshell spawning (other than for a ulimit call if we want to get a decent upper limit on FD numbers).

    fd=2 max=$(ulimit -n)
    
    while ((++fd < max)); do
       ! true <&$fd && break
    done 2>/dev/null && echo $fd
    
    • Basically we just iterate over possible FDs until we reach one we can't dupe.
    • In order to avoid the Bad file descriptor error message from the last loop iteration, we redirect stderr for the whole while loop.

提交回复
热议问题