0

I have this:

 chmod u+x $(find scripts -name "*.sh")

But I believe it's only running chmod u+x for the first item in the list from find, since the results are newline separated.

How can I run chmod u+x for each item returned from the find call?

My guess is that xargs is the best way? something like this:

 find scripts -name "*.sh" | xargs chmod u+x
Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
Alexander Mills
  • 9,330
  • 19
  • 95
  • 180
  • Your belief is not accurate. What happens when you run it that makes you think it's doing that? Are there any unusual file names or file permissions? – Michael Homer Apr 27 '18 at 04:55
  • nah no unusual filenames...wouldn't the xargs command be different than the first one? if one command, works the other shouldn't.. – Alexander Mills Apr 27 '18 at 05:02
  • Why do you think that those commands can’t both work? (Ignoring file names with whitespace etc.) – Stephen Kitt Apr 27 '18 at 05:45
  • Uhh with the first one, since the find command returns newline separate results, I wasn't under the impression that `chmod u+x` (or any similar command) can handle that – Alexander Mills Apr 27 '18 at 06:53
  • 1
    Oh, `chmod` doesn’t need to handle newlines in the result of a command substitution: the shell parses everything (and it [removes newlines from the output](https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html#Command-Substitution)). – Stephen Kitt Apr 30 '18 at 09:02
  • @StephenKitt thanks I didn't know that! – Alexander Mills Apr 30 '18 at 16:22

1 Answers1

2

The safest way to do this is to let find execute chmod directly, and also to be more careful in the selection of the files:

find scripts -type f -name '*.sh' -exec chmod u+x {} +

This will find all regular files in or below the scripts directory that have names that end with .sh and will run chmod u+x on as many of these as possible at once. It will handle possibly weird filenames without issues.

To change the permissions on only those files that needs it:

find scripts -type f -name '*.sh' ! -perm -u+x -exec chmod u+x {} +
Kusalananda
  • 320,670
  • 36
  • 633
  • 936