Automating Git Cleanup Across Multiple Directories with a Shell Script

Learn how to reset all Git repositories in a directory to their clean and original state efficiently.

Managing multiple Git repositories can be a tedious task.
One task I often perform is ensuring each repository is clean and reset to its original state.
Instead of manually navigating into each directory and running Git commands, I like to automate the process with a simple shell script.

Objective of the Script

This script automates two key tasks for all Git repositories in the current working directory:

  1. git clean -fdx: Removes untracked files, directories, and ignored files.
  2. git reset --hard HEAD: Resets the repository to the last commit, discarding all local changes.

The script loops through each directory, checks if it’s a Git repository, and then performs the cleanup operations.

Solution

Let’s create a script called git-cleanup.sh.

touch git-cleanup.sh
chmod +x git-cleanup.sh

Now, write the script using your favorite text editor, such as vim:

#!/bin/sh

# Loop through each directory
for dir in */; do
  if [ -d "$dir/.git" ]; then
    echo "Cleaning $dir"
    (cd "$dir" && git clean -fdx && git reset --hard HEAD)
  fi
done

Once it’s done, you can use it like this:

cd path/to/directories
./git-cleanup.sh

Here’s What Each Line Does:

  1. for dir in */;: Loops through each directory in the current working directory. The trailing / ensures that only directories are considered.
  2. [ -d "$dir/.git" ]: Checks if the directory contains a .git folder, confirming that it’s a Git repository.
  3. (cd "$dir" && git clean -fdx && git reset --hard HEAD):
    • cd "$dir" changes into the repository directory.
    • git clean -fdx removes all untracked and ignored files.
    • git reset --hard HEAD discards any local changes and resets to the latest commit.
    • Parentheses ( ... ) ensure the directory change (cd) is temporary and scoped to the command group.
  4. echo "Cleaning $dir": Provides visual feedback about which directory is being processed.

When to Use This Script

  • Reset Development Environments: Quickly reset all repositories to their clean state.
  • Batch Cleanup: Remove temporary files or untracked changes from all repositories.
  • Post-Merge Cleanup: After working across multiple repositories, ensure none are left in a dirty state.

⚠️ WARNING!

This script will permanently delete untracked files and discard local changes in all Git repositories.
Make sure that you don’t need any unsaved changes or untracked files before running it.
Once deleted, the untracked files are gone forever!

Use at your own risk!

Conclusion

This simple shell script is an efficient tool to clean up multiple Git repositories.
Whether you’re a solo developer managing microservices or part of a larger team, this script can streamline your workflow.

Thanks for reading, and see you next time!