Friday, May 6, 2022

[SOLVED] Why doesn't chmod -R +x *.sh work?

Issue

So, "chmod -R +x *.sh" does not work in bash. Alternatives can be found href="https://stackoverflow.com/questions/4249878/how-do-i-change-file-permission-to-a-certain-file-pattern-to-sub-folders-of-my-c">here. My question is: why doesn't it work? Does chmod simply lack this feature because nobody bothered to implement it or is there some deeper bash/gnulib philosophy to this?


Solution

This is because in bash, the wildcard pattern is expanded by the shell and not by the program. This is unlike in Windows where the pattern is passed to the program itself. Let's consider this sample directoy structure:

curdir
|_ 1.sh
|_ 2.sh
|_ subdir
   |_ 3.sh
   |_ 4.sh

Say you're running the command chmod -R +x *.sh from within the curdir directory. The shell sees that *.sh is a wildcard pattern and expands it to 1.sh 2.sh since those are the filenames that match the pattern. The final command that is executed becomes chmod -R +x 1.sh 2.sh. As you can see, none of the arguments is a directory, so the -R switch has no effect.

There are shells that have support for more complex patterns. For example, if you're using zsh, you can run the following command:

chmod +x **/*.sh # Note that -R is not required

zsh understands the ** pattern to mean a recursive search into subdirectories. Thus, the final command in this case will be:

chmod +x 1.sh 2.sh subdir/3.sh subdir/4.sh


Answered By - svsd
Answer Checked By - Clifford M. (WPSolving Volunteer)