Skip to content

Instantly share code, notes, and snippets.

@MrSunshyne
Created September 11, 2024 07:27
Show Gist options
  • Save MrSunshyne/35dd7dcf8a6bb9d2e2fde5cd6b9393cd to your computer and use it in GitHub Desktop.
Save MrSunshyne/35dd7dcf8a6bb9d2e2fde5cd6b9393cd to your computer and use it in GitHub Desktop.
Pre-commit hook that prevents you from accidentally git comitting as a different user
#!/bin/bash
# Setup
# touch ~/.git/hooks/pre-commit
# chmod +x ~/.git/hooks/pre-commit
# git config --global core.hooksPath ~/.git/hooks
# Get the current user email
user_email=$(git config --global user.email)
user_email=$(git config --global user.email)
# Define allowed and disallowed email lists (modify as needed)
allowed_emails=(
"[email protected]"
"[email protected]"
)
disallowed_emails=(
"[email protected]"
)
# Check if email is in the allowlist
if [[ ! "${allowed_emails[@]}" =~ "$user_email" ]]; then
# Check if email is in the disallowlist
if [[ "${disallowed_emails[@]}" =~ "$user_email" ]]; then
echo "🛑 Error: Your git user email ($user_email) is disallowed for committing."
else
echo "🚨 Error: Your git user email ($user_email) is not authorized to commit. Please use an allowed email address."
fi
exit 1 # Exit with non-zero code to abort commit
fi
# If email is allowed, proceed with commit
echo "Current git user email is $user_email"
@k3ii
Copy link

k3ii commented Sep 11, 2024

Use #!/usr/bin/env bash instead of #!/bin/bash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment