4

How can I use chown -R but exclude one or two files?

I periodically need to run

sudo chown -R www-data:www-data *

and

sudo chown -R ubuntu:ubuntu *

But I'd like to exclude one or two files from those commands as to not change the permissions of those excluded files.

How can I exclude file1.php, or both file2.txt and file3.php?

1
  • Could you consider allowing permission change on all files, and then reinstating the permissions for those two files?
    – pierrely
    Jul 20, 2019 at 6:04

1 Answer 1

7

Set bash’s extglob option with

shopt -s extglob

and use it like that to exclude these files:

sudo chown -R www-data:www-data !(file1.php)
sudo chown -R ubuntu:ubuntu !(file2.txt|file3.php)

This works with files and directories equally, but only in the current directory. If you need to exclude files in subdirectories, combine the above with the globstar option (shopt -s globstar):

sudo chown -R www-data:www-data **/!(file1.php)

This matches every file and directory except the ones called file1.php.

Example run

$ touch {1..3}
$ shopt -s extglob
$ echo !(1)
2 3
$ echo !(1|2)
3
$ mkdir a
$ touch a/{1..3}
$ tree
.
├── 1
├── 2
├── 3
└── a
    ├── 1
    ├── 2
    └── 3
$ shopt -s globstar
$ echo **/!(1|2)
3 a a/3

Further reading

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .