When I have
exec 3>>file # file descriptor 3 now points to file
[ $dryrun ] && exec 3>&1 # or possibly to stdout
echo "running">&3
exec 3>&- # and is now closed
I’m worried about what file descriptor 3 may have pointed to outside of the function in question. How can I handle this?
- Is there a builtin
next_available_fd? - Is there a way to duplicate fd3 to a variable, then dup it back once the function is done?
- and should I worry about threading and concurrent writes to fd3 in this case?
- I’m in sh, but maybe bash/ksh/zsh has an answer to this?
Instead of using exec to redirect the file descriptor within the function, you can (with bash, I haven’t tried with other shells) do:
foo() { test $dryrun && exec 3>&1 echo running >&3 } 3>>file foo more_commandsIn this setup, “running” will go to either the file or to the original stdout depending on $dryrun, and more_commands will have fd 3 as it was before foo was called.