I've got a perl script that I run from root but sudoed as apache. Like so:

# sudo -u apache /usr/bin/perl /path/to/script.pl

The script uses File::Find to parse a directory. Bascially it does something like this:
#!/usr/bin/perl -w use strict; use File::Find; my @dirList = ('/dir/to/parse'); find(\&wanted, @dirList); sub wanted { print "Processing: $File::Find::name\n"; } print "done.\n";
The problem is that if you are in the "/root" directory when you try this, you end up with the script doing some processing but then it dies out with: "Can't cd to /root: Permission denied". The same error shows up if you try to run the script in the root crontab with something like:

1 * * * * sudo -u apache /usr/bin/perl /path/to/script.pl

I looked around for a while to see if anyone else was running into this but my searches didn't return anything. After some playing around I came up with the following that seems to work for me:

#!/usr/bin/perl -w use strict; use File::Find; use FindBin; chdir($FindBin::RealBin); my @dirList = ('/dir/to/parse'); find(\&wanted, @dirList); sub wanted { print "Processing: $File::Find::name\n"; } print "done.\n";

Figured I'd post here in case it helps someone else, but I'm also curious if this is the best way to do this or what other options are.

In reply to File::Find with sudo from root by anotherSmith

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.