sh: How do I avoid clobbering numbered file descriptors? sh: How do I avoid clobbering numbered file descriptors? unix unix

sh: How do I avoid clobbering numbered file descriptors?


I don't know about anything as simple as next_available_fd, but to get the functionality that you want (temporarily redirecting a file descriptor without affecting it outside the function) can be accomplished as follows in bash (I don't know about sh):

exec 3>file3exec 1>file1echo "something">&3echo "something else"f31 () {        echo "something">&3}f31 3>&1f13 () {        echo "something else"}f13 >&3echo "something">&3echo "something else"

The resulting file1:

something elsesomethingsomething else

And file3:

somethingsomething elsesomething

Which demonstrates that the redirection is restricted to the function call in each case.


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

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


If your system uses the /proc filesystem, look inside /proc/$$/fd to see what's in use.