2

Right now, I have a script that runs daily that chmod's the home directories, removing all "other" permissions from the directories and the "group" write permission. See below.

#Removing all other permissions on all home directories and write from group

ls /home | sed 's/ //g' |
while read i; do
  chmod -R o-rwx /home/$i
  chmod -R g-w /home/$i
done

This works great; however, I would prefer if the script checked if there were any files that needed to be changed and then act upon them instead of just doing it every time, regardless if it needs it.

I assume I could put this whole thing in a sub function inside of a if statement, but I don't know what test I would run inside that if statement.

How can I test if the directories would need changed?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
TrevorKS
  • 638
  • Checking first is very likely to be be slower. Just run for dir in /home/*/; do chmod -R g-w,o-rwx "$dir"; done unless you want to do something else with the files with extra permissions, like get a listing of them before fixing the permissions. – ilkkachu Aug 06 '18 at 18:38
  • You can configure default permissions for all sub-items inside home directory with setfacl. https://unix.stackexchange.com/questions/1314/how-to-set-default-file-permissions-for-all-folders-files-in-a-directory – BufferOverflow Aug 07 '18 at 22:41

1 Answers1

3

Use find:

find /home/* -type d -maxdepth 0 -perm /g+w,o+rwx -exec chmod g-w,o-rwx '{}' +

If you want to do this recursive, as you use -R in your examples, use this

find /home/* -perm /g+w,o+rwx -exec chmod g-w,o-rwx '{}' +

Edit:

Brief explanation of find options, for details see man find:

The -perm together with /mode means any of the bits is set.

The classical -exec syntax is -exec command '{}' ';'. The characters {} are replaced with the file name, the quotes are there to protect them from the shell, on most shells this is not necessary, but it doesn't hurt. The ';' is the end of the command, here quoting is necessary for most shells, but an alternative form is \;. The drawback is that there is one call to chmod per file changed. This is avoided with the alternative form where the command is terminated with +. This form calls exec with many names, and is in effect similar to xargs, it even saves the overhead of calling xargs.

RalfFriedl
  • 8,981