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<
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