Can you change permission to all files except one directory in Linux?

20,411

Solution 1

Assuming that you wish to set the permission bit 755 recursively for the contents of the folders in your current working directory, apart from the contents of the folder called "nameOfFolderToBeExcluded":

 chmod 755 -R $(ls | awk '{if($1 != "nameOfFolderToBeExcluded"){ print $1 }}')

Solution 2

You can use find to search for all the files that does not match the given filename and exec a command on all such files found as:

Assuming you need to exclude directory test and give file permissions 755 to all other files and directores. This would be excecuted from the top of the tree.

find ! -name test -exec chmod 755 {} \;

Tested

mtk@mtk4-laptop:$ touch a1.txt a2.txt a3.txt test
mtk@mtk4-laptop:$ ls -lrt
total 0
-rw-rw-r-- 1 mtk mtk 0 Sep 17 23:55 test
-rw-rw-r-- 1 mtk mtk 0 Sep 17 23:55 a3.txt
-rw-rw-r-- 1 mtk mtk 0 Sep 17 23:55 a2.txt
-rw-rw-r-- 1 mtk mtk 0 Sep 17 23:55 a1.txt
mtk@mtk4-laptop:$ find ! -name test -exec chmod 777 {} \;
mtk@mtk4-laptop:$ ls -lrt
total 0
-rw-rw-r-- 1 mtk mtk 0 Sep 17 23:55 test
-rwxrwxrwx 1 mtk mtk 0 Sep 17 23:55 a3.txt*
-rwxrwxrwx 1 mtk mtk 0 Sep 17 23:55 a2.txt*
-rwxrwxrwx 1 mtk mtk 0 Sep 17 23:55 a1.txt*
mtk@mtk4-laptop:$ 

The file permissions for file test remained unchanged. Same is applicable for directories.

Solution 3

What shell?

If you're running bash (likely if you're on Linux), you can check out extglob, which gives you more options for globbing, including the "negative glob" !()

shopt -s extglob
chmod 774 !(file-to-ignore)

Solution 4

Using find more simply like this:

find <from_where_to_change> -not -path "*/<excluded_dir_name>*" [-and -not -path "*/<another_excluded_dir_if_you_want>*"] -exec chown <user>[:<group>] {} \;

In my case it was:

find /data/project -not -path "*/.svn*" -exec chown :www-data {} \;

This way I changed group on folder /data/project recursively, except all folders ".svn" recursively.

Share:
20,411

Related videos on Youtube

Rana
Author by

Rana

Software Engineer, Technology Enthusiast, Blogger.

Updated on September 18, 2022

Comments

  • Rana
    Rana over 1 year

    Is there any way to change all files/directories permission except one single directory in a single Linux command line command?

    • Admin
      Admin over 11 years
      grep -v "directory to exclude"
  • Kraang Prime
    Kraang Prime over 7 years
    This only exclude files by that name -- not folders. Try mkdir test + touch a1.txt a2.txt a3.txt, and then execute the command.
  • Ashark
    Ashark about 4 years
    Why not just use -I (--ignore) option of ls?