[Israel.pm] Renaming folder using perl

sawyer x xsawyerx at gmail.com
Tue May 5 06:46:22 PDT 2009


Hi

> I need to write a script that renames the folder the script is running from:
> The idea to rename the current folder to a back_<localtime>, then download a
> zip file and extract it

This seems like something that should fail regardless of the rename.
It's insecure, can cause FS problems and doesn't make a lot of sense.
Why does the script have to be run from within a folder that needs to
be renamed? In UNIX (I'm not sure how it is with Windows), there is no
"renaming" folders function. It doesn't exist. You "mv" stuff. That
doesn't just rename it, it gives it a different inode and everything.
That means that - to the OS and FS - it's not the same folder. This
detaches the script's environment, making it much easier to
compromise. Beyond that, you can have serious errors trying to change
or fetch environment variables. When running with FS functions, it
usually calls environment variables or uses the environment in some
way which a good point to target when trying to compromise the script.

> (the main Idea to replace the current agent with another nagios agent).

This shouldn't be run from the same folder that is being moved.

> Problem: how can I rename the current folder the script is running from ?
> trying rename function fails (like system rename).

There is no original "rename" function in UNIX. There is a "rename"
utility Larry Wall wrote, that helps you change files. Sort of like
perl -pi -e.
If you want to use UNIX system commands, there's "mv" - as I've stated
above. I think you better check modules that provide portability:
File::Rename, File::PerlMove. I'm not sure if they support folders,
since it's a bit trickier.

My advice on your act is:
- Don't ever change the environment of a script like that
- Run the script from outside
- Do an atomic operation with rename so it wouldn't be a problem (such
as File::Transaction::Atomic, File::AtomicWrite)


Also, you should use File::Spec in order to avoid knowing whether to
use "../" or "..\" - not to mention Mac OS paths.

Sawyer.


More information about the Perl mailing list