Ternary
Ternary

Reputation: 597

sh: How do I avoid clobbering numbered file descriptors?

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?

Upvotes: 7

Views: 236

Answers (3)

William Pursell
William Pursell

Reputation: 212168

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

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246744

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

Upvotes: 0

trutheality
trutheality

Reputation: 23455

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>file3
exec 1>file1

echo "something">&3
echo "something else"

f31 () {
        echo "something">&3
}
f31 3>&1

f13 () {
        echo "something else"
}
f13 >&3

echo "something">&3
echo "something else"

The resulting file1:

something else
something
something else

And file3:

something
something else
something

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

Upvotes: 1

Related Questions