Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
1 total  XML / RSS feed 

Save & restore file permissions with xattr

Extended attributes make it possible to store (additional) file metadata on a per-file basis. This can, for example, be used to save & restore file permissions.


mkdir -p ~/Desktop/testdir
touch ~/Desktop/testdir/f{1,2,3}.txt
find -x ~/Desktop/testdir -print0 | xargs -0 stat -LF
stat -x ~/Desktop/testdir/f1.txt

which xattr   # /opt/local/bin/xattr; sudo port install xattr (after installing MacPorts, http://www.macports.org/install.php)


# store file permissions as additional Unix file metadata with xattr

find -x ~/Desktop/testdir -print0 | while read -d $'\0' filename; do
#find -x ~/Desktop/testdir -type f -or -type d -print0 | while read -d $'\0' filename; do
   fchmod="$(stat -f %p "$filename")"; \
   fchown="$(stat -f %u:%g "$filename")"; \
   xattr --set fchmod "$fchmod" "$filename"; \
   xattr --set fchown "$fchown" "$filename"; \
   #echo $fchown $fchmod; \
done


find -x ~/Desktop/testdir -print0 | xargs -0 xattr --list
find -x ~/Desktop/testdir -print0 | xargs -0 stat -LF

# change file permissions & ownership
sudo chown -R root:wheel ~/Desktop/testdir
sudo chmod -R 700 ~/Desktop/testdir

sudo find -x ~/Desktop/testdir -print0 | xargs -0 sudo stat -LF
find -x ~/Desktop/testdir -print0 | xargs -0 xattr --list
sudo find -x ~/Desktop/testdir -print0 | xargs -0 sudo xattr --list


# restore file permissions & ownership

sudo find -x ~/Desktop/testdir -print0 | while read -d $'\0' filename; do 
   fchown="$(sudo xattr --get fchown "$filename" | awk '/fchown/ {print $2}')"; \
   fchmod="$(sudo xattr --get fchmod "$filename" | awk '/fchmod/ {print $2}')"; \
   sudo chown "$fchown" "$filename"; \
   sudo chmod "$fchmod" "$filename"; \
   #echo $fchown $fchmod; \
done


find -x ~/Desktop/testdir -print0 | xargs -0 stat -LF
find -x ~/Desktop/testdir -print0 | xargs -0 xattr --list


« Newer Snippets
Older Snippets »
1 total  XML / RSS feed