How to find next available file descriptor in Bash?

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

    I decided to summarize the brilliant answer given by @paxdiablo into the single shell function with two auxiliary ones:

    fd_used_sym() {
        [ -e "/proc/$$/fd/$1" ]
    }
    
    fd_used_rw() {
        : 2>/dev/null >&$1 || : 2>/dev/null <&$1
    }
    
    fd_free() {
        local fd_check
        if [ -e "/proc/$$/fd" ]
        then
            fd_check=fd_used_sym
        else
            fd_check=fd_used_rw
        fi
    
        for n in {0..255}
        do
            eval $fd_check $n || {
                echo "$n"
                return
            }
        done
    }
    

    There is sort of simplifications -- escape from auxiliary functions without losing the main functionality:

    fd_free() {
        local fd_check
        if [ -e "/proc/$$/fd" ]
        then
            fd_check='[ -e "/proc/$$/fd/$n" ]'
        else
            fd_check=': 2>/dev/null >&$n || : 2>/dev/null <&$n'
        fi
    
        for n in {0..255}
        do
            eval $fd_check || {
                echo "$n"
                return
            }
        done
    }
    

    Both functions check availability of the file descriptor and output the number of the first found free file descriptor. Benefits are following:

    • both check ways are implemented (via /proc/$$/fd/X and R/W to a particular FD)
    • builtins are used only

提交回复
热议问题