Is it possible to create a script to save and restore permissions?
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
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