Resolve Drupal Git Error: unable to unlink old (Permission denied)

One of the most common errors you might face working with Drupal locally is "error: unable to unlink old...: Permission denied". Now let's go through this scenario and see why it happens and how to fix it.

Why did it happen?

You are working on a Drupal project locally and are trying to do a git checkout and move to a different branch but now you have an error of GIT not able to unlink file and a modified file.

git checkout develop                                                                                                                       
error: unable to unlink old 'docroot/sites/default/settings.php': Permission denied
Checking out files: 100% (13948/13948), done.
M	docroot/sites/default/settings.php
Switched to branch 'develop'
Your branch is behind 'upstream/develop' by 9 commits, and can be fast-forwarded.
  (use "git pull" to update your local branch)

As you can see above GIT recommends doing a "git pull" but it doesn't work. After this, you can also try to use "sudo" and checkout the settings.php file which messes up things even more.

So what is the solution?

How to fix it?

The first thing we need to understand is this is not the issue with the file but with the directory itself, which most probably has permission 'w'.

So you can run the chmod command to give the parent directory permissions to write for the user and group.

chmod ug+w sites/default

This is will fix your git error "unable to unlink old (Permission denied)" and you should be able to simply checkout the settings.php file to revert the changes

Now you are good to go back to your Drupal stuff.