How to backup and restore permissions of the entire directory on Linux

The following two commands getfacl and setfacl are very handy tools as they allow Linux administrators to take a snapshot of any current permissions settings of any directory and if needed re-apply those permissions back recursively. Let’s have a look at the following example:

$ tree -p
.
โ”œโ”€โ”€ [dr---w----]  dir1
โ”‚ย ย  โ””โ”€โ”€ [drwxr-xr-x]  dir2
โ”‚ย ย      โ”œโ”€โ”€ [dr--r-xrw-]  dir3
โ”‚ย ย      โ””โ”€โ”€ [---x--x--x]  file1
โ”œโ”€โ”€ [drwxr-xr-x]  dir4
โ”‚ย ย  โ””โ”€โ”€ [-rw-r--r--]  file3
โ””โ”€โ”€ [-rwxrwxrwx]  file2

4 directories, 3 files

The above output list all files and directories in a tree like structure along with all relevant permissions for each file and directory. Now we use getfacl command in order to make a backup of all permissions for each file and directory:

$ getfacl -R . > permissions_backup

The above command saved all permissions including an ownership for each file and directory recursively into a file called permissions_backup.

# cat permissions_backup 
# file: .
# owner: lubos
# group: lubos
user::rwx
group::r-x
other::r-x

# file: file2
# owner: lubos
# group: lubos
user::rwx
group::rwx
other::rwx

# file: dir4
# owner: lubos
# group: lubos
user::rwx
group::r-x
other::r-x

# file: dir4/file3
# owner: lubos
# group: lubos
user::rw-
group::r--
other::r--

# file: dir1
# owner: lubos
# group: lubos
user::r--
group::-w-
other::---

# file: dir1/dir2
# owner: lubos
# group: lubos
user::rwx
group::r-x
other::r-x

# file: dir1/dir2/dir3
# owner: lubos
# group: lubos
user::r--
group::r-x
other::rw-

# file: dir1/dir2/file1
# owner: lubos
# group: lubos
user::--x
group::--x
other::--x

Next, we change all permissions:

$ chmod -R 777 .
$ tree -p
.
โ”œโ”€โ”€ [drwxrwxrwx]  dir1
โ”‚ย ย  โ””โ”€โ”€ [drwxrwxrwx]  dir2
โ”‚ย ย      โ”œโ”€โ”€ [drwxrwxrwx]  dir3
โ”‚ย ย      โ””โ”€โ”€ [-rwxrwxrwx]  file1
โ”œโ”€โ”€ [drwxrwxrwx]  dir4
โ”‚ย ย  โ””โ”€โ”€ [-rwxrwxrwx]  file3
โ”œโ”€โ”€ [-rwxrwxrwx]  file2

As we can see all permissions are changed and now we can use setfacl command along with our permissions backup file generated previously to restore former permission settings:

$ setfacl --restore=permissions_backup 
$ tree -p
.
โ”œโ”€โ”€ [dr---w----]  dir1
โ”‚ย ย  โ””โ”€โ”€ [drwxr-xr-x]  dir2
โ”‚ย ย      โ”œโ”€โ”€ [dr--r-xrw-]  dir3
โ”‚ย ย      โ””โ”€โ”€ [---x--x--x]  file1
โ”œโ”€โ”€ [drwxr-xr-x]  dir4
โ”‚ย ย  โ””โ”€โ”€ [-rw-r--r--]  file3
โ”œโ”€โ”€ [-rwxrwxrwx]  file2


Comments and Discussions
Linux Forum