Saturday, 10 February 2007

Linux: Changing file and dirctory permisions for an entire directory tree

Suppose you have a directory named /mydir and you need to change the permissions on all the files for the entire directory tree. Using a command like chmod -R 644 * might get you into trouble since this may change execute (i.e. traversal) access even for existing directories.

A friend from Germany (thanks Antoni) gave me the fhis solution :

First the files

find /mydir -type f -exec chmod 0644 {} \;

... and then the directories

find /mydir -type d -exec chmod 0755 {} \;

Note: The previous commands reset the file permissions completely. If you want to just add read access, while preserving the rest, you might prefer a u+r or g+r command line to chmod as in the following example which adds read and execute access to /mydir and all it's subdirectories.

find /mydir -type d -exec chmod u+rx {} \;

By the way, since I have lately found to need this more and more - as I move data to and from USB sticks -- I created a simple script that given a directory gives all files permissions 0644 and all directories 0755

#!/bin/bash
# File resetPerms.sh

if [ -d $1 ]
then
  echo Reseting file and directory access on $1
  find $1 -type f -exec chmod 0644 {} \;
  find $1 -type d -exec chmod 0755 {} \;
fi

2 comments :

Μονότροπος said...

Informative notes Thanassis and useful!

For chmod it's safer to use 0644 for file permissions mask, so only their owner will be able to write to them.

On the other hand, if you use the GNU chmod, there is a '-R' option for recursive chmod (although it can't distinguish files from directories or filter them like find does).

Athanassios Bakalidis said...

Thanks for that I already changed the original post to write "chmod 644"