How can I change file and directory permissions in one go via SSH?

0

I'm trying to use find in conjunction with -exec and chmod to recursively change the permissions on every file and directory inside a folder via SSH.

I want to do these two commands in one line:

find /share/Multimedia/ -type f -exec chmod 644 {} \;
find /share/Multimedia/ -type d -exec chmod 755 {} \;

I was able to find a solution prior that someone else posted somewhere and for some reason my bash command history was cleared and I did not write down the syntax I was using elsewhere for reference. I don't often do this so I'm not too savvy on standard Unix commands.

I was using something along the lines of:

# probably won't execute
find /share/Multimedia/ ( if -type f -exec chmod 644 {} \; else if -type d -exec chmod 755 {} \; )

I only want to run this on my NAS every now and then to normalize permissions in one go, possibly unattended to do something else in the meantime while my NAS processes it.

SebinNyshkim

Posted 2016-11-15T22:30:34.817

Reputation: 103

Answers

1

You can take advantage of the and-or structure of find's expression system to do this:

find /share/Multimedia/ -type f -exec chmod 644 {} \; -o -type d -exec chmod 755 {} \;

Essentially, this has the following logic:

IF:
    the item is a plain file
    AND the chmod 644 command succeeds on it
OR
    the item is a directory
    AND the chmod 755 command succeeds on it
THEN
    ... well, do nothing; normally it'd print the item's path, but since
    there's a -exec in the expression, that gets skipped

But there's actually a much simpler way:

chmod -R u=rwX,go=rX /share/Multimedia/

This takes advantage of chmod's "X" permission, which means "execute, but only if it makes sense". Mostly, that means it sets execute on directories, but not plain files. The main potential problem is that if it sees an execute permission on a plain file, it assumes it's intentional and keeps it, so this won't clean up after someone goes through and assigns execute permission to everything.

Gordon Davisson

Posted 2016-11-15T22:30:34.817

Reputation: 28 538

That's kind of the thing, my NAS sets kind of arbitrary permissions on new files and I want to normalize them to how I feel comfortable of permissions on files and directories. Thanks for the thorough explanation. I think the first one was what I was looking for :) – SebinNyshkim – 2016-11-27T17:19:39.293

2

First of all, if is a keyword for shell, not for find, you can't use it as an option.

Second, you are probably looking for something like that :

find /share/Multimedia/ -exec sh -c 'if [ -f {} ]; then chmod 644 {}; else chmod 755 {}; fi' \;

We are just checking if element is a file with our shell with if [ -f {} ] then we chmod as you wanted for a file or for a directory.

Suicideboy

Posted 2016-11-15T22:30:34.817

Reputation: 21