Bash script to change files permissions to match those of existing file

Alec Jacobson

October 25, 2010

weblog/

Found this handy bash one-liner to print the "ls -l" results refixed by the files' octal permissions (as in 644, 707, etc.):
ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf("%0o ",k);print}'
I added a few things so that I code write a program that found the premissions of a given file and applied them to another file. Essentially changing a file's permissions to match the permissions of another existing file. I save this in match-chmod.sh:
#!/bin/bash
#
# To set permissions of file_two to match permissions of file_one, issue:
# match-copy file_one file_two
octal_permissions=`ls -l $1 |\
  awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf("%0o",k);}'`
chmod $octal_permissions $2
Depending on the permissions of file two you may or may not need to use 'sudo'. Source: http://www.linuxforums.org/forum/newbie/21722-command-shows-me-permissions-file-octal.html