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

Viewed 18352

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?

13 Answers

I modified Anton`s command to get the additional string chown user:group /file_or_folder_path. Now you can get a bash script which contains two string for each file/folder.

command:

find . -type f | xargs stat -c "%a %U:%G %n" | awk '{print "chown "$2" "$3"\nchmod "$1" "$3}' > ./filesPermissions.sh

Example of output:

chown root:root /file_or_folder_path
chmod 777 /file_or_folder_path

I borrow this answer from roaima's post.
I think this should be the best answer:
Save the permissions

find * -depth -exec stat --format '%a %u %g %n' {} + >/tmp/save-the-list

Restore the permissions

while read PERMS OWNER GROUP FILE
do
    chmod "$PERMS" "$FILE"
    chown "${OWNER}:${GROUP}" "$FILE"
done </tmp/save-the-list
Related