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 t
save: find . -type f |xargs ls -la| awk '{print "chmod "$1" "$NF}'>./filesPermissions.sh
restore: sh ./filesPermissions.sh
I found the answer from Dmytro L very cool. But, unfortunately, it's doesn't work, because it's generate entries like:
chmod -rw-r--r-- ./.bashrc
To avoid it, I use following command:
find . -type f | xargs stat -c "%a %n" | awk '{print "chmod "$1" "$2}' > ./filesPermissions.sh
Basically, it does the same, but generate octal entries like:
chmod 644 ./.bashrc
which works.
Here's an example for easily doing this with a single file. No additional tools, scripts, temp file, etc. are required. You could expand upon this method for working with more files if needed.
In this specific example, the permissions are saved in a varibale via the stat
command. Then, the file is temporarily stripped of any restrictive permissions. Next, something is done with it (that may have failed due to those prior restrictions). Finally, the original permissions are restored.
file=$1
saved_permissions=$(sudo stat -c %a $file)
sudo chmod 777 $file
# <DO SOMETHING HERE>
sudo chmod $saved_permissions $file
#!/bin/bash
if [ $# -ne 1 ]; then
echo "Enter directory";
exit 0;
fi
# dump acls
cd $1
>acl
echo "#!/bin/bash">recovery_acl.sh
echo "cd $1">>recovery_acl.sh
f='./'
# create acl file sorted by dir_level
for i in `seq 0 15`;do
find . -mindepth $i -maxdepth $i -type d -exec getfacl {} +|grep -E '*UTS|file:'>>acl
done
sed -i 's/default\:user/\-dm\ u/g' acl
sed -i 's/default\:group/\-dm\ g/g' acl
sed -i 's/user\:/\-m\ u\:/g' acl
sed -i 's/group\:/\-m\ g\:/g' acl
sed -i 's/\#\ file\:\ /\.\//g' acl
sed -i '/^#/d' acl
while IFS='' read -r line ; do
# grep dir name
if echo "$line" | grep -q "$f" ; then
dir="$line"
continue
fi
echo setfacl $line '"'$dir'"'>>recovery_acl.sh
# grep non def acl (for files)
if echo "$line" | grep -q '\-m' ; then
echo setfacl $line '"'$dir'"'/*>>recovery_acl.sh
fi
done < "acl"
rm -f acl
sed -i 's/134/\\/g' recovery_acl.sh
sed -i 's/040/\ /g' recovery_acl.sh
After execution of script, will creating another "recovery_acl.sh". Replace UTS on your domain. Errors like "No such file or directory" means that dir is empty.
you can get the file's permissions with
ls -l | awk '{print $1" "$NF}'
which will return a list of file names and their permissions. save it somewhere, and once you're done - restore (chmod) each file's permissions.
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