I'd like to make a bash script output additional information to file descriptors (FDs) greater than or equal to 3, when they are open. To test whether an FD is open, I devised the following trick:
if (printf '' 1>&3) 2>&-; then
# File descriptor 3 is open
else
# File descriptor 3 is not open
fi
This is sufficient for my needs, but I'm curious as to whether there is a more idiomatic way of testing if an FD is valid. I'm especially interested about whether there exists a mapping of the fcntl(1)
syscall to a shell command, which would allow the retrieval of FD flags (O_WRONLY
and O_RDWR
to test whether the FD is writable, and O_RDONLY
and O_RDWR
to test whether the FD is readable).