MacOS – OSX Bash for loop – issues with spaces in folder names

bashmacospermissionscriptterminal

I'm getting a bit confused on how to handle spaces in path names when returned in a for loop.

Rationale: I'm cleaning up the permissions on folders and files that I copy over from Windows. Most of the files end up with -rwx------ or -rwxr-xr-x permissions so I like to do "chmod -x *" and then "chmod u+x <folders>" so I'm trying the following:

$ alias getdirs='find . -maxdepth 1 -mindepth 1 -type d | cut -c 3-'
$ for i in $(getdirs); do chmod u+x $i; done

which works fine, as long as the directories don't have a space in the name.

I've tried different permutations of chmod u+x "$i", chmod u+x '$i' and similar to get the behavior I wanted, but to no avail.

How to improve my bash code, that works with folder names containing space?

The purpose of this is to be able to remove the "exec" bit from plain files (hence the chmod -x * part) but then to restore it to the directories to allow getting into them (chmod u+x <dirname>). From the comments and answers so far I'm thinking that it probably will be easier to do with the proper "find" incantation

Best Answer

These kind of things can be tricky in all Unix shells due to the way space is acting as a separator, running aliases as part of shell scripts just makes things even more interesting. I would probably run two passes of find to set first the directories in order, and then next the files:

find . -maxdepth 1 -mindepth 1 -type d -exec chmod u+x '{}' \;
find . -maxdepth 1 -mindepth 1 -type f -exec chmod u-x '{}' \;