in reply to Why does File::Find try to chdir to $PWD (and fail) even if $PWD is not itself in search list?

You're already putting in the effort to change user IDs. Why stop there? If it doesn't matter to the search what the current working directory is, just take one more step and change the current working directory in the code before the find. That way it'll try to change back to that directory instead of the one from which the program was run.

When the program exits, any path changes will be lost anyway. Your prompt will still come back to your shell's current working directory since environment changes do not flow upstream.

I recommend using chdir to change to the root directory for sake of portability, but you could make it any other directory the account can access.

Below is some example code. I can run this as root in root's home directory without any errors. It changes to my non-root account, changes to the root ('/', not to be confused with '/root') directory, searches a directory my non--root account can access (and actually owns in this case, but that's not important), and File::Find returns to '/' when it's done.

use File::Find; $< = $> = 500; sub w { print $_ . "\n" } chdir q(/); find( \&w, qw( /home/chris/Pictures ) );

There's no reason for File::Find not to return to the directory from which it started. There's also no reason to have it return to a directory where the user account under which it is operating has no privileges. No code that might be executed afterward would have rights to that directory either anyway.

  • Comment on Re: Why does File::Find try to chdir to $PWD (and fail) even if $PWD is not itself in search list?
  • Download Code

Replies are listed 'Best First'.
Re^2: Why does File::Find try to chdir to $PWD (and fail) even if $PWD is not itself in search list?
by puterboy (Scribe) on Nov 26, 2008 at 07:24 UTC
    Thanks - that makes a lot of sense. I hadn't considered that changing directory to root or elsewhere is harmless since it doesn't outlast the routine.
      The root directory will tend to be readable by all users by default anyway. A directory that's by default world-readable is the ideal place to not have permission errors upon reading.

      Many daemon programs actually change directory to '/' as one of the first things they do. Some others are written to have a specific directory set up just for a chroot jail.