mkpath equivalent for chown [Perl]
How can I execute chown for all the directories on a given path (similar to mkpath in perl).
i.e. if I give 开发者_运维问答/home/parth/something/else and as input, all of the directories on this path will have that owner. Is there an inbuilt function ?
There are no built-in functions for it. However, you can use the core module File::Find
to traverse directory tree, getpwnam
to get UID, and chown
to change ownership.
#!/usr/bin/env perl
use strict;
use warnings;
use File::Find;
sub usage {
die "Usage: $0 USERNAME PATH\n";
}
my $username = shift or die usage;
my $uid = ( getpwnam $username )[2] or die "Non-existent user.\n";
my $path = shift or die usage;
if ( !-e $path ) {
die "Non-existent path.\n";
}
find( \&traverse, $path );
sub traverse {
chown $uid, -1, $_ or die "Failed to chown [$_]: $!";
}
Usage
chown_path USERNAME PATH
Use File::Find::Rule
to identify the files to change, then use chown
on the files found.
use File::File::Rule qw( );
my $uid = getpwnam('...') or die;
my $gid = getgrnam('...') or die;
for my $qfn (File::Find::Rule->in('/home/parth/something/else')) {
chown($uid, $gid, $qfn)
or warn("chown $qfn: $!\n");
}
精彩评论