Search code examples
linuxperluid

How to get owner:group name of a file/directory with perl?


There is a great method to output permissions on Linux and AIX:

0:root@SERVER:/root # perl -e 'printf "chmod %04o %s\n", (stat)[2] & 07777, $_ for @ARGV' /home      
chmod 0755 /home
0:root@SERVER:/root #

But how to output owner:group? ex.:

0:root@SERVER:/root # perl SOMEMAGIC /home
chown bin:bin /home
0:root@SERVER:/root #

UPDATE: currently I almost figured it out, only help needed that if there is a symlink, it will give root:root. It should give the owner:group of the symlink!

perl -e '$uid = (stat)[4], $_ for @ARGV; $owner = getpwuid($uid); $gid = (stat)[5], $_ for @ARGV; $group = getgrgid($gid); print "chown $owner:$group \"@ARGV\"\n"' FILENAMEHERE

UPDATE2: with lstat, it works!


Solution

  • Use stat to get the uid/gid, and getpwnam/getgrnam to convert those into names.

    If symlinks are involved you might get better results by using lstat instead of stat:

    perl -e '$uid = (lstat)[4], $_ for @ARGV; $owner = getpwuid($uid); $gid = (lstat)[5], $_ for @ARGV; $group = getgrgid($gid); print "chown $owner:$group \"@ARGV\"\n"' FILENAMEHERE