In a Bash-script, is it possible to open a file on \"the lowest-numbered file descriptor not yet in use\"?
I have looked around for how to do this, but it seems that Bas
I needed to support both bash v3 on Mac and bash v4 on Linux and the other solutions require either bash v4 or Linux, so I came up with a solution that works for both, using /dev/fd
.
find_unused_fd() {
local max_fd=$(ulimit -n)
local used_fds=" $(/bin/ls -1 /dev/fd | sed 's/.*\///' | tr '\012\015' ' ') "
local i=0
while [[ $i -lt $max_fd ]]; do
if [[ ! $used_fds =~ " $i " ]]; then
echo "$i"
break
fi
(( i = i + 1 ))
done
}
For example to dup stdout, you can do:
newfd=$(find_unused_fd)
eval "exec $newfd>&1"