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

I periodically need to run

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


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?

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

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)
$ 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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.