Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a script to save and restore permissions?

I am using a linux system and need to experiment with some permissions on a set of nested files and directories. I wonder if there is not some way to save the permissions for the files and directories, without saving the files themselves.

In other words, I'd like to save the perms, edit some files, tweak some permissions, and then restore the permissions back onto the directory structure, keeping the changed files in place.

Does that make sense?

like image 953
NinjaCat Avatar asked Sep 05 '25 17:09

NinjaCat


2 Answers

The easiest way is to use ACL tools, even if you don't actually use ACLs. Simply call getfacl -R . >saved-permissions to back up the permissions of a directory tree and setfacl --restore=saved-permissions to restore them.

Otherwise, a way to back up permissions is with find -printf. (GNU find required, but that's what you have on Linux.)

find -depth -printf '%m:%u:%g:%p\0' >saved-permissions

You get a file containing records separated by a null character; each record contains the numeric permissions, user name, group name and file name for one file. To restore, loop over the records and call chmod and chown. The -depth option to find is in case you want to make some directories unwritable (you have to handle their contents first).

You can restore the permissions with this bash snippet derived from a snippet contributed by Daniel Alder:

while IFS=: read -r -d '' mod user group file; do
  chown -- "$user:$group" "$file"
  chmod "$mod" "$file"
done <saved-permissions

You can use the following awk script to turn the find output into some shell code to restore the permissions.

find -depth -printf '%m:%u:%g:%p\0' |
awk -v RS='\0' -F: '
BEGIN {
    print "#!/bin/sh";
    print "set -e";
    q = "\047";
}
{
    gsub(q, q q "\\" q);
    f = $0;
    sub(/^[^:]*:[^:]*:[^:]*:/, "", f);
    print "chown --", q $2 ":" $3 q, q f q;
    print "chmod", $1, q f q;
}' > restore-permissions.sh
like image 91
Gilles 'SO- stop being evil' Avatar answered Sep 07 '25 13:09

Gilles 'SO- stop being evil'


Install the ACL package first:

sudo apt-get install acl

Recursively store permissions and ownership to file:

getfacl -R yourDirectory > permissions.acl

Restore (relative to current path):

setfacl --restore=permissions.acl
like image 45
durandal Avatar answered Sep 07 '25 13:09

durandal