How can I chmod/chown a specific list of files?

32

5

I want to write a .sh script to setup some folder permissions, but was wonder if I can run something like:

chown -644 ./one;/two;/three

to chown a list of folders, rather than calling chown multiple times.

Also, would there be a way to chown a list of files, and exclude some others, like for example:

chown -R -664 ./*;!./cache

I hope my pseudo command lines make sense.

josef.van.niekerk

Posted 2013-01-29T09:19:52.270

Reputation: 1 553

Answers

44

Almost all Unix tools accept a list of files as non-option arguments. As usual, the different arguments have to be separated by space:

chown 644 one two three

In your second example, if you're using Bash, a simple

chown -R 644 !(cache)

will be enough.

This approach requires extended pattern matching. If it's disabled, you can enable it with

shopt -s extglob

See: Bash Reference Manual # Pattern Matching

Dennis

Posted 2013-01-29T09:19:52.270

Reputation: 42 934

4

Make a list of filenames in ./list-of-filenames-to-change.txt and then run:

chmod g+w `cat list-of-filenames-to-change.txt`

or use the method described by others here:

chmod 644 one two three

or go to town with the first option but manipulate each line in the file (in this example: replace " /" (WITH whitespace before) by " ./"):

chmod g+w `sed 's/ \// .\//' update-writable.txt` 

Chonez

Posted 2013-01-29T09:19:52.270

Reputation: 41

2

If the files you want to modify are in one directory you can ls them with the needed pattern.

e.g. I need all downloaded .run files in pwd to be changed to executable:

chmod +x `ls *.run`

gat1

Posted 2013-01-29T09:19:52.270

Reputation: 21

2

regex for the win!

using find is the best way I can think of outside of using the regex that may already exist in your particular shell or within the app you are using itself. first, I tried:

touch one&touch two &touch three&find -name "one|two|three" -exec chown -644 {} \;

But, you'll find that the pipe doesn't work in this case. Another sad thing to learn...like learning chmod,chown,chgrp,et. al. doesn't support multi-file/regex selection/exclusion itself...
The solution I found:
https://stackoverflow.com/questions/19111067/regex-match-either-string-in-linux-find-command

find \( -name one -o -name two -o -name three \) -exec chown -644 {} \;

so, not so much regex for the win, but at least we have a way to inject a list of files into the args of a program in a one liner.

you'll note that you need to escape the () meta-characters, and the addition of the -o parameter for each additional name...

other links and content from me which might interest you along your travels:
Various tidbits - notes from korn bourne and friends. - Dave Horner's Website

Cheers.
--dave

Dave Horner

Posted 2013-01-29T09:19:52.270

Reputation: 193

KISS win, Keep it simple and stupid ! no need to complex things that can be still clean and easy. – Al-Mothafar – 2016-11-20T13:10:14.967