Copy chmod permissions from one file to another

This script demonstrates how to copy the permissions of one file to another file so that they both have the same permissions. For example, if the first file is read-only, then the second file will be made read-only too.

#!/home/ben/software/install/bin/perl
use warnings;
use strict;
use utf8;
use File::Slurper qw/read_binary write_binary/;
my $filea = "$0";
my $text = read_binary ($filea);
my $fileb = "$filea-copy";
if (-f $fileb) {
    unlink $fileb or die $!;
}
write_binary ($fileb, $text);
my $permissionsa = (stat ($filea))[2];
my $permissionsb = (stat ($fileb))[2];
printf ("A: %s - %o\n", $filea, $permissionsa);
printf ("B before: %s - %o\n", $fileb, $permissionsb);
chmod $permissionsa, $fileb or die $!;
$permissionsb = (stat ($fileb))[2];
printf ("B after: %s - %o\n", $fileb, $permissionsb);

(download)

The program's output looks like this:

$ perl copy-chmod.pl 
A: copy-chmod.pl - 100755
B before: copy-chmod.pl-copy - 100644
B after: copy-chmod.pl-copy - 100755

Web links


Copyright © Ben Bullock 2009-2019. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer