4

I have problems with the working of the chown function in Perl. I have a script:

#!/usr/bin/perl

$file   = "";
$file   = $ARGV[0];

$user   = "jboss";
$group  = "jboss";

if ($file eq "")
{
    print "Syntax: $0 <file>\n";
    exit 0;
}

@file = ($file);

print "Chowning the file $file to $user:$group\n";

$number = chown $user, $group, "$file";

print "Number of ownerships changed: $number\n";

exit 0;

SELinux is enabled and permissive, but:

root# ls -l file 
-rw-r--r--. 1 root root 0 Jul 26 10:27 file  
root# id -a jboss uid=666(jboss) gid=666(jboss) groups=666(jboss)  
root# perlchown_file.pl file   
Chowning the file file to jboss:jboss  
Number of ownerships changed: 1  
root# ls -l file 
-rw-r--r--. 1 root root 0 Jul 26 10:27 file

Question: what do I miss here ? Of course you can write a qx("/usr/bin/chown jboss:jboss ") here, but the whole point here is to use a more platform independent function here, and not a backtick quote

1
  • In the future you better ask stackoverflow for that kind of question.
    – Déjà vu
    Jul 31, 2016 at 17:55

2 Answers 2

13

Perl's chown function expects a numeric uid/gid instead of a user/group name. See perldoc -f chown.

To get the uid from the user name and the gid from the group name, you can use the getpwnam and getgrnam functions like this:

my $uid = getpwnam $user_name;
my $gid = getgrnam $group_name;
chown $uid, $gid, $file_name;
0
3

If you had used use warnings; you would have gotten an error message complaining that:

Argument "jboss" isn't numeric in chown...

This would have given you the hint that you needed UID and GID instead of user and group. It's always a good idea to start every Perl script with use warnings and use strict.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.