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