46

Using chmod, I do chmod +x *.sh in the current directory but what if I want to change all files including files within subfolders that has an sh file extension?.

chmod +x -R * will work but I need something more like chmod +x -R *.sh

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
ivanceras
  • 1,415
  • 3
  • 17
  • 28

3 Answers3

80

use find:

find . -name "*.sh" -exec chmod +x {} \;
ennuikiller
  • 46,381
  • 14
  • 112
  • 137
  • 1
    the command line is hard to memorize or remember, I have to come and visit this page often times to see the syntax. Do you have a sort of way to remember this command? – ivanceras Jan 07 '11 at 15:52
  • I can't remember a lot of the commands. So, I build scripts that accept parameters. – Nathan Feb 17 '14 at 22:03
  • 1
    For those confused about what the command is actually *doing*, see chappjc's answer, below, for a hint, at least. – Dan Nissenbaum Jan 14 '18 at 04:08
13

Try using the glorious combination of find with xargs.

find . -iname \*.sh -print0 | xargs -r0 chmod +x

The . is the directory to start in, in this case the working directory.

LookAheadAtYourTypes
  • 1,629
  • 2
  • 20
  • 35
Orbling
  • 20,413
  • 3
  • 53
  • 64
  • Or you can use -exec in the simple case, as in ennuikiller's example. `xargs` has slightly more power for more complicated uses. – Orbling Nov 22 '10 at 20:28
  • 1
    This is more efficient than find ... -exec ... See http://en.wikipedia.org/wiki/Xargs – Nathan Feb 17 '14 at 22:05
  • @Nathan Thanks for pointing out this important distinction. Reading about this, I discovered a newish `find` syntax that gets the best of both worlds (see [my answer](http://stackoverflow.com/a/32618572/2778484) for details). – chappjc Sep 16 '15 at 20:59
8

With modern versions of find, you get the benefits of an xargs approach that avoids multiple calls to the command (chmod). The command is only slightly different.

find . -name "*.sh" -exec chmod +x {} +

Snip from find docs on Arch 2015.09.01 (emphasis added by me):

-exec command {} +

This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of {} is allowed within the command. The command is executed in the starting directory.

Community
  • 1
  • 1
chappjc
  • 30,359
  • 6
  • 75
  • 132