In bash, once a fd is in use (either as input or output):
exec 7>AFile
It seems that that fd number could be duplicated, both as input or output:
true <&7; echo $?
true >&7; echo $?
The tests could be repeated for a variable as:
fd=7
rco="$(true >&${fd} 2>/dev/null; echo $?)"
rci="$(true <&${fd} 2>/dev/null; echo $?)"
And both exit values joined in one word as:
[[ "$rco$rci" = "11" ]] && echo "The fd number $fd is free"
The question is:
Under which conditions will the exit value of "$rco$rci"
be different of 11
for a "free" fd number.
In other words: could it be 10
or 01
sometimes?
Could it be either in other shells?
Never. Under the hood, the redirections will attempt to dup an existing or free filedescriptor and then the shell should proceed to run
true
if the preliminary redirections succeeded.dup
ing from an unopen descriptor should always fail, which effectively means one attempted redirection in either direction should be enough to test whether a filedescriptor is open or not.( Conversely,
dup
ing from an open descriptor should almost always succeed. It fails when you've run out of your per-process filedescriptor limit which is usually 1024-4096, and you could theoretically get a permission fail if the shell tried to reset the open flags, but dash, bash, and zsh don't appear to try to do this. I only get IO errors when I actually try to write to a duped readonly filedescriptor, not during the redirection. )