Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

share|improve this question

2 Answers 2

up vote 4 down vote accepted

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;
share|improve this answer
    
Thank you for that, RTFM, I guess :-) –  Willem Jul 26 '13 at 9:42

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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