How to chmod 755 all directories but no file (recursively) ?

Inversely, how to chmod only files (recursively) but no directory ?

link|improve this question

46% accept rate
feedback

4 Answers

Directories,

find /path/to/base/dir -type d -exec chmod 755 {} \;

Files:

find /path/to/base/dir -type f -exec chmod 755 {} \;

If there are few objects to process,

 chmod 755 $(find /path/to/base/dir -type d)

And like Chris says -- to reduce chmod spawning,

find /path/to/base/dir -type d -print0 | xargs -0 chmod 755 
find /path/to/base/dir -type f -print0 | xargs -0 chmod 755 
link|improve this answer
1  
If there are “lots” of directories/files, it might be worth it to use xargs to avoid spawning one chmod process per entry: find /path/to/base/dir -type d -print0 | xargs -0 chmod 755. – Chris Johnsen Jan 6 '10 at 6:06
feedback

A common reason for this sort of thing is to set directories to 755 but files to 644. In this case there's a slightly quicker way than nik's find example:

chmod -R u+rwX,go+rX,go-w /path
link|improve this answer
o_O Would you be able to dissect that command for us? Thanks! – Babu Jan 6 '10 at 4:46
1  
-R = recursively; u+rwX = Users can read, write and execute; go+rX = group and others can read and execute; go-w = group and others can't write – släcker Jan 6 '10 at 7:08
11  
The important thing to note here is that X acts differently to x - the man page says The execute/search bits if the file is a directory or any of the execute/search bits are set in the original (unmodified) mode. In other words, chmod u+X on a file won't set the execute bit; and g+X will only set it if it's already set for the user. – James Polley Jan 6 '10 at 9:34
1  
The upper case X is the key here guys... – toor Jun 6 '11 at 16:46
feedback

If you want to make sure the files are set to 644 and there are files in the path which have the execute flag, you will have to remove the execute flag first. +X doesn't remove the execute flag from files who already have it.

Example:

chmod -R ugo-x,u+rwX,go+rX,go-w path

Update: this appears to fail because the first change (ugo-x) makes the directory unexecutable, so all the files underneath it are not changed.

link|improve this answer
feedback

You could use the following bash script as an example. Be sure to give it executable permissions (755). Simply use ./autochmod.sh for the current directory, or ./autochmod.sh <dir> to specify a different one.

#!/bin/bash

if [ -e $1 ]; then
    if [ -d $1 ];then
        dir=$1
    else
        echo "No such directory: $1"
        exit
    fi
else
    dir="./"
fi

for f in $(ls -l $dir | awk '{print $8}'); do
    if [ -d $f ];then
        chmod 755 $f
    else
        chmod 644 $f
    fi
done
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.