Fix Git Repository Ownership and Permissions
Recursively changes ownership of the .git directory to the current user and sets appropriate permissions for Git operations. This command resolves common permission issues that occur when Git repositories are created or modified with root privileges.
sudo chown -R $(whoami):$(whoami) .git && sudo chmod -R ug+rwx,o+rx .git
Categories
Operating Systems
cross-platform
Prerequisites
Unix-like operating system (Linux, macOS, WSL)
sudo privileges
Basic understanding of file permissions and ownership
Last Tested
5/29/2025
Details
This compound command performs two critical operations:
-
Ownership Change (
chown -R $(whoami):$(whoami) .git
)- Changes both user and group ownership of the entire .git directory tree
$(whoami)
dynamically gets the current username-R
flag applies changes recursively to all subdirectories and files
-
Permission Setting (
chmod -R ug+rwx,o+rx .git
)ug+rwx
: Grants read, write, and execute permissions to user and groupo+rx
: Grants read and execute permissions to others (no write access)-R
flag applies permissions recursively
Common Use Cases:
- After cloning a repository with sudo
- When Git operations fail with "Permission denied" errors
- After accidentally running Git commands as root
- When switching between different user accounts on the same repository
- Resolving issues after copying repositories between systems
Example Scenarios:
# When you see errors like:
# fatal: could not lock config file .git/config: Permission denied
# error: insufficient permission for adding an object to repository database
# Run the fix command:
sudo chown -R $(whoami):$(whoami) .git && sudo chmod -R ug+rwx,o+rx .git
# Then verify with:
ls -la .git/
Safety Notes
- Always run this command from the repository root directory
- Verify you're in the correct directory before execution
- The command uses sudo, so ensure you understand the implications
- Consider backing up important repositories before making permission changes
Related Articles
Blog posts that might provide additional context