Precommit hook to discard all submodule changes

pre-commitShell

pre-commit

#!/bin/bash
# Git pre-commit hook: Discards all changes in submodules before committing. (.git/hooks/pre-commit)

set -e
echo "Discarding all changes in submodules before commit..."

# Reset and clean all submodules recursively
git submodule foreach --recursive '
  git reset --hard
  git clean -fdx
'

# Unstage any superproject submodule pointer updates, so submodule state never changes
if [ -f .gitmodules ]; then
  git config --file .gitmodules --get-regexp path | awk "{print \\$2}" | while read submodule
  do
    if git diff --cached --name-only | grep -q "^$submodule"; then
      git reset HEAD "$submodule"
    fi
  done
fi

echo "All submodule changes have been discarded and unstaged."
Updated: 5/7/2025