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<
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
Bad file descriptor error message from the last loop iteration, we redirect stderr for the whole while loop.