Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Script: Changing file permissions recursively

I need a Bash script that changes the file permissions of all files in a directory and all subdirectories. It should behave like this:

for each file in directory (and subdirectories)
   if i am the owner of the file
      if it is a directory
         chmod 770 file
      else
         chmod 660 file

I guess it's not a difficult task but I am not very experienced in Bash scripts. Your help is appreciated! :D

like image 258
Auron Avatar asked May 23 '17 07:05

Auron


People also ask

How do I change permissions recursively?

If you need to change a file permission, use the chmod command. It also allows to change the file permission recursively to configure multiple files and sub-directories using a single command.

How do I change permissions on multiple files?

Chmod allows you to change the permission of multiple files and subdirectories within a directory using the –R option as follows: $ chmod –R [reference][operator][mode] file... Let's say the subdirectories under the downloads directory have the following permissions as shown in the following screenshot.

How do I change permissions on Ubuntu recursively?

Fortunately, you can recursively change the file permissions of a directory or file and its sub-directories and files. To do that, use the chmod command recursive -r option.

Why we use chmod 777?

Setting 777 permissions to a file or directory means that it will be readable, writable and executable by all users and may pose a huge security risk.


1 Answers

You could do it with two invocations of the find command, with the -user option to filter by user, and the -type option to filter by filetype:

find . -user "$USER" -type d -exec echo chmod 770 {} +
find . -user "$USER" -not -type d -exec echo chmod 660 {} +

Remove echo after testing, to actually change the permissions.

like image 184
user000001 Avatar answered Sep 17 '22 18:09

user000001