Recursively fix bad file permissions

Ever found yourself changing permissions recursively and then realise you used the wrong permissions? Unfortunately, I have. Don’t know if it was due to lack of sleep or caffeine but it just did.

Due to my bad handling, I had a few folders where the permissions got screwed up. The folders that I needed to fix didn’t exist just out of files. There where also different folders present that went N-levels deep.

Luckily, with some bash scripting, I was able to fix them again.

Bash to the rescue

I used this simple script to reset the permissions again. The script uses -find- to list all directories and files, with chmod to reset the permissions.


export IFS=$'\n'

for x in ${directory[@]} do
  for i in $(find $x -type d) do
    chmod 755 $i

  for i in $(find $x -type f) do
    chmod 664 $i

As you can see, we start of by building an array of directories where we set the bad permissions. In the above example, all files and folders under project_A, project_C, project_F and project_K needed to be reset.

We store those root folders in the directory array.

Then we set the IFS variable. The IFS variable is used by for loops to determine what the field separators are. Since we will be using the find command inside a for loop, we will need to set the field separator to \n ( newline ). When you for instance type in:

$ find . -type d

you will see all directories and subdirectories inside the current folder are listed, each directory on a new line.

Next, we loop over the directory array. During the project directory loop, we then look for all the folders inside the project root folder, using the find command in conjunction with the -type d option. This way, we have a list of all subdirectories on all levels. We then loop the directory list and change the permissions back to 755 using the chmod command.

In analogy, when then find all files, again, using the find command, but this time usingthe -type f option, so we have a list of all files available on all levels. We then loop that list as well and change the permissions of all files to 644.

Keep in mind that this will set all folders to 755 and all files to 644. So if you have executable files somewhere, you will need to catch this, so you can make them executable again.

Then just save the file, make it executable and run it.