Master Git configuration, aliases, hooks, and advanced settings to customize your Git workflow and boost productivity.
<p>
Git is highly configurable, allowing you to tailor it to your exact workflow needs.
From simple aliases to complex automation hooks, mastering Git configuration transforms
you from a Git user into a Git power user.
</p>
<p>
In this lesson, we'll explore the full spectrum of Git configuration options, from basic
settings to advanced automation that can save you hours of repetitive work and prevent
costly mistakes.
</p>
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 1.5rem; border-radius: 8px; margin: 1.5rem 0;">
<h4 style="color: white; margin: 0 0 0.5rem 0;">⚙️ Configuration Impact</h4>
<p style="color: rgba(255,255,255,0.9); margin: 0;">
Proper Git configuration can reduce command typing by 70%, automate code quality checks,
and prevent common errors before they reach your repository.
</p>
</div>
<p>
Git uses a three-tier configuration system, with each level overriding the previous one.
Understanding this hierarchy is essential for managing settings across different projects and teams.
</p>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1rem; margin: 1.5rem 0;">
<div style="background: #1e293b; padding: 1.5rem; border-radius: 8px; border-left: 4px solid #ef4444;">
<h5 style="color: #ef4444; margin: 0 0 0.5rem 0;">System Level</h5>
<code style="font-size: 0.85rem; color: #94a3b8;">git config --system</code>
<p style="margin: 0.5rem 0; color: #cbd5e1; font-size: 0.9rem;">
Applies to all users and repositories on the machine. Requires admin privileges.
</p>
<p style="margin: 0.5rem 0 0 0; color: #64748b; font-size: 0.85rem;">
Location: /etc/gitconfig or C:ProgramDataGitconfig
</p>
</div>
<div style="background: #1e293b; padding: 1.5rem; border-radius: 8px; border-left: 4px solid #f59e0b;">
<h5 style="color: #f59e0b; margin: 0 0 0.5rem 0;">Global Level</h5>
<code style="font-size: 0.85rem; color: #94a3b8;">git config --global</code>
<p style="margin: 0.5rem 0; color: #cbd5e1; font-size: 0.9rem;">
Applies to all repositories for the current user. Most common for personal settings.
</p>
<p style="margin: 0.5rem 0 0 0; color: #64748b; font-size: 0.85rem;">
Location: ~/.gitconfig or C:Users[user].gitconfig
</p>
</div>
<div style="background: #1e293b; padding: 1.5rem; border-radius: 8px; border-left: 4px solid #22c55e;">
<h5 style="color: #22c55e; margin: 0 0 0.5rem 0;">Local Level</h5>
<code style="font-size: 0.85rem; color: #94a3b8;">git config --local</code>
<p style="margin: 0.5rem 0; color: #cbd5e1; font-size: 0.9rem;">
Applies only to the current repository. Overrides global and system settings.
</p>
<p style="margin: 0.5rem 0 0 0; color: #64748b; font-size: 0.85rem;">
Location: .git/config (inside repository)
</p>
</div>
</div>
<h4>Essential Configuration Commands</h4>
1# View all configuration settings
2git config --list --show-origin
3
4# Set user identity (global)
5git config --global user.name "Your Name"
6git config --global user.email "[email protected]"
7
8# Set default branch name
9git config --global init.defaultBranch main
10
11# Set default editor
12git config --global core.editor "code --wait" # VS Code
13git config --global core.editor "vim" # Vim
14
15# Enable color output
16git config --global color.ui auto
17
18# Set up credential caching
19git config --global credential.helper cache
20git config --global credential.helper 'cache --timeout=3600'
21
22# View specific setting
23git config user.name
24
25# Unset a configuration
26git config --global --unset user.email<p>
Git aliases let you create shortcuts for frequently used commands, combining multiple operations
into single commands that match your workflow perfectly.
</p>
<h4>Basic Aliases</h4>
1# Simple command shortcuts
2git config --global alias.co checkout
3git config --global alias.br branch
4git config --global alias.ci commit
5git config --global alias.st status
6
7# Now you can use:
8git co main
9git br -a
10git ci -m "message"
11git st<h4>Advanced Aliases with Arguments</h4>
1# Pretty log with graph
2git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
3
4# Show last commit
5git config --global alias.last 'log -1 HEAD'
6
7# Undo last commit (keep changes)
8git config --global alias.undo 'reset HEAD~1 --mixed'
9
10# List aliases
11git config --global alias.aliases "config --get-regexp ^alias."
12
13# Amend last commit without editing message
14git config --global alias.amend 'commit --amend --no-edit'
15
16# Show changed files in last commit
17git config --global alias.changed 'show --name-only'
18
19# Stage all changes and commit
20git config --global alias.ac '!git add -A && git commit'
21
22# Create new branch and switch to it
23git config --global alias.cob 'checkout -b'<h4>Complex Workflow Aliases</h4>
1# Delete merged branches (excluding main/master)
2git config --global alias.cleanup "!git branch --merged | grep -v '\*\|main\|master' | xargs -n 1 git branch -d"
3
4# Pull with rebase and autostash
5git config --global alias.up 'pull --rebase --autostash'
6
7# Show contributors with commit count
8git config --global alias.contributors 'shortlog -sn'
9
10# Find commits by message
11git config --global alias.find '!git log --all --grep'
12
13# Show branches sorted by last commit
14git config --global alias.recent "branch --sort=-committerdate"
15
16# Interactive rebase with main
17git config --global alias.rim 'rebase -i main'
18
19# Sync fork with upstream
20git config --global alias.sync '!git fetch upstream && git checkout main && git merge upstream/main'<div style="background: #0f172a; padding: 1rem; border-left: 4px solid #3b82f6; border-radius: 4px; margin: 1rem 0;">
<strong style="color: #3b82f6;">💡 Pro Tip:</strong>
<p style="margin: 0.5rem 0 0 0; color: #cbd5e1;">
Aliases starting with <code>!</code> are executed as shell commands, giving you access to
the full power of bash scripting within Git aliases.
</p>
</div>
<p>
Git hooks are scripts that run automatically at specific points in the Git workflow.
They're perfect for enforcing code quality, running tests, and preventing common mistakes.
</p>
<h4>Common Git Hooks</h4>
<table>
<thead>
<tr>
<th>Hook</th>
<th>When It Runs</th>
<th>Common Uses</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>pre-commit</code></td>
<td>Before commit is created</td>
<td>Linting, formatting, tests</td>
</tr>
<tr>
<td><code>commit-msg</code></td>
<td>After commit message entered</td>
<td>Message format validation</td>
</tr>
<tr>
<td><code>pre-push</code></td>
<td>Before push to remote</td>
<td>Run test suite, security checks</td>
</tr>
<tr>
<td><code>post-checkout</code></td>
<td>After successful checkout</td>
<td>Install dependencies, setup</td>
</tr>
<tr>
<td><code>post-merge</code></td>
<td>After successful merge</td>
<td>Update dependencies, migrations</td>
</tr>
</tbody>
</table>
<h4>Example: Pre-commit Hook</h4>
1#!/bin/sh
2# .git/hooks/pre-commit
3
4echo "Running pre-commit checks..."
5
6# Run linter
7npm run lint
8if [ $? -ne 0 ]; then
9 echo "❌ Linting failed. Commit aborted."
10 exit 1
11fi
12
13# Run tests
14npm test
15if [ $? -ne 0 ]; then
16 echo "❌ Tests failed. Commit aborted."
17 exit 1
18fi
19
20# Check for debugging statements
21if git diff --cached | grep -E "console.(log|debug|info)"; then
22 echo "❌ Found console statements. Please remove them."
23 exit 1
24fi
25
26echo "✅ All checks passed!"
27exit 0<h4>Example: Commit Message Hook</h4>
1#!/bin/sh
2# .git/hooks/commit-msg
3
4commit_msg_file=$1
5commit_msg=$(cat "$commit_msg_file")
6
7# Enforce conventional commits format
8# Format: type(scope): subject
9pattern='^(feat|fix|docs|style|refactor|test|chore)((.+))?: .{1,50}'
10
11if ! echo "$commit_msg" | grep -qE "$pattern"; then
12 echo "❌ Invalid commit message format!"
13 echo "Format: type(scope): subject"
14 echo "Types: feat, fix, docs, style, refactor, test, chore"
15 echo ""
16 echo "Examples:"
17 echo " feat(auth): add login functionality"
18 echo " fix(api): handle null responses"
19 echo " docs: update README"
20 exit 1
21fi
22
23echo "✅ Commit message format valid"
24exit 0<h4>Example: Pre-push Hook</h4>
1#!/bin/sh
2# .git/hooks/pre-push
3
4protected_branches="main master production"
5current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/(.*),,')
6
7for branch in $protected_branches; do
8 if [ "$current_branch" = "$branch" ]; then
9 echo "❌ Direct push to $branch is not allowed!"
10 echo "Please use a pull request."
11 exit 1
12 fi
13done
14
15# Run full test suite before push
16echo "Running test suite..."
17npm test
18if [ $? -ne 0 ]; then
19 echo "❌ Tests failed. Push aborted."
20 exit 1
21fi
22
23echo "✅ Push checks passed!"
24exit 0<div style="background: #fef3c7; padding: 1rem; border-left: 4px solid #f59e0b; border-radius: 4px; margin: 1rem 0;">
<strong style="color: #92400e;">⚠️ Important:</strong>
<p style="margin: 0.5rem 0 0 0; color: #78350f;">
Git hooks are not version controlled. Use tools like <strong>Husky</strong> to share hooks
across your team and ensure consistent quality checks for all contributors.
</p>
</div>
<h4>Setting Up Husky (Recommended)</h4>
1# Install Husky
2npm install --save-dev husky
3npx husky install
4
5# Add pre-commit hook
6npx husky add .husky/pre-commit "npm run lint && npm test"
7
8# Add commit-msg hook
9npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'
10
11# Add pre-push hook
12npx husky add .husky/pre-push "npm test"<p>
<code>.gitignore</code> and <code>.gitattributes</code> files give you fine-grained control
over which files are tracked and how Git handles them.
</p>
<h4>Advanced .gitignore Patterns</h4>
1# Ignore all .log files
2*.log
3
4# But track important.log
5!important.log
6
7# Ignore all files in any directory named temp
8**/temp/
9
10# Ignore all .txt files in the doc/ directory but not subdirectories
11/doc/*.txt
12
13# Ignore all .pdf files in doc/ and subdirectories
14doc/**/*.pdf
15
16# Ignore files matching pattern
17build-*.jar
18test-[0-9].js
19
20# Ignore OS specific files
21.DS_Store
22Thumbs.db
23desktop.ini
24
25# Ignore IDE files
26.vscode/
27.idea/
28*.swp
29*.swo
30
31# Ignore environment files
32.env
33.env.local
34.env.*.local
35
36# Ignore dependency directories
37node_modules/
38vendor/
39packages/
40
41# Ignore build outputs
42dist/
43build/
44*.min.js
45*.min.css
46
47# Ignore log and temporary files
48*.log
49*.tmp
50*.temp
51logs/
52tmp/
53
54# Ignore package manager lock files (if needed)
55package-lock.json
56yarn.lock
57pnpm-lock.yaml<h4>.gitattributes for Consistent Behavior</h4>
1# Auto detect text files and normalize line endings to LF
2* text=auto
3
4# Force LF line endings for these files
5*.sh text eol=lf
6*.bash text eol=lf
7Dockerfile text eol=lf
8
9# Force CRLF line endings for Windows scripts
10*.bat text eol=crlf
11*.cmd text eol=crlf
12
13# Binary files (don't try to merge or diff)
14*.png binary
15*.jpg binary
16*.gif binary
17*.ico binary
18*.pdf binary
19*.zip binary
20*.gz binary
21
22# Mark generated files
23package-lock.json linguist-generated=true
24yarn.lock linguist-generated=true
25
26# Custom diff for specific files
27*.json diff=json
28*.md diff=markdown
29
30# Merge strategies for specific files
31package.json merge=ours
32README.md merge=union
33
34# Filter large files through Git LFS
35*.psd filter=lfs diff=lfs merge=lfs -text
36*.ai filter=lfs diff=lfs merge=lfs -text
37*.zip filter=lfs diff=lfs merge=lfs -text<h4>Creating Global .gitignore</h4>
1# Create global gitignore file
2touch ~/.gitignore_global
3
4# Add OS and editor files
5echo ".DS_Store" >> ~/.gitignore_global
6echo "Thumbs.db" >> ~/.gitignore_global
7echo ".vscode/" >> ~/.gitignore_global
8echo ".idea/" >> ~/.gitignore_global
9
10# Configure Git to use it
11git config --global core.excludesfile ~/.gitignore_global<div style="background: #0f172a; padding: 1rem; border-left: 4px solid #3b82f6; border-radius: 4px; margin: 1rem 0;">
<strong style="color: #3b82f6;">💡 Pro Tip:</strong>
<p style="margin: 0.5rem 0 0 0; color: #cbd5e1;">
Use <a href="https://gitignore.io" target="_blank" style="color: #60a5fa;">gitignore.io</a>
to generate comprehensive .gitignore files for your specific tech stack.
</p>
</div>
<p>
These advanced settings enhance security, performance, and workflow efficiency.
</p>
<h4>Security Settings</h4>
1# Sign commits with GPG
2git config --global user.signingkey YOUR_GPG_KEY_ID
3git config --global commit.gpgsign true
4
5# Require signed pushes
6git config --global push.gpgSign if-asked
7
8# Enable SSH key signing (Git 2.34+)
9git config --global gpg.format ssh
10git config --global user.signingkey ~/.ssh/id_ed25519.pub
11
12# Prevent commits to specific branches
13git config --global branch.main.protected true
14
15# Warn before pushing to origin
16git config --global push.confirm true<h4>Performance & Behavior</h4>
1# Enable parallel operations
2git config --global fetch.parallel 0 # Auto-detect CPU cores
3git config --global submodule.fetchJobs 4
4
5# Improve performance for large repositories
6git config --global core.preloadindex true
7git config --global core.fscache true
8git config --global gc.auto 256
9
10# Set default pull strategy
11git config --global pull.rebase true
12
13# Automatically prune on fetch
14git config --global fetch.prune true
15
16# Enable rerere (reuse recorded resolution)
17git config --global rerere.enabled true
18
19# Set merge conflict style
20git config --global merge.conflictstyle diff3
21
22# Limit diff context lines for performance
23git config --global diff.context 5<h4>Commit and Merge Settings</h4>
1# Set default merge strategy
2git config --global merge.ff false # Always create merge commit
3
4# Automatically resolve simple conflicts
5git config --global merge.autostash true
6
7# Show file moves in diff
8git config --global diff.renames true
9
10# Colorize moved lines in diff
11git config --global diff.colorMoved default
12
13# Set commit template
14git config --global commit.template ~/.gitmessage
15
16# Auto-correct typos
17git config --global help.autocorrect 1<h4>Example Commit Template (~/.gitmessage)</h4>
1# Type: (feat|fix|docs|style|refactor|test|chore)
2# Scope: (component|module affected)
3#
4# Subject: Brief description (50 chars)
5# |<---- Preferably using up to 50 chars ---->|
6
7
8# Body: Detailed explanation (wrap at 72 chars)
9# |<---- Try To Limit Each Line to a Maximum Of 72 Characters ---->|
10
11
12# Footer: Issue references, breaking changes
13# Example:
14# Fixes #123
15# BREAKING CHANGE: API endpoint changed from /api/v1 to /api/v2
16
17# Type options:
18# - feat: A new feature
19# - fix: A bug fix
20# - docs: Documentation only changes
21# - style: Code style changes (formatting)
22# - refactor: Code change that neither fixes a bug nor adds a feature
23# - test: Adding missing tests or correcting existing tests
24# - chore: Changes to build process or auxiliary tools<h4>Useful Configuration Queries</h4>
1# Show all configuration with sources
2git config --list --show-origin
3
4# Show only global configuration
5git config --global --list
6
7# Get value of specific setting
8git config --get user.email
9
10# Get all values for a key (if multiple)
11git config --get-all remote.origin.fetch
12
13# Edit config file directly
14git config --global --edit
15
16# Remove a configuration
17git config --global --unset user.email
18
19# Remove entire section
20git config --global --remove-section user<div style="background: #1e293b; padding: 1.5rem; border-radius: 8px; margin: 1.5rem 0;">
<h4 style="margin: 0 0 1rem 0; color: #60a5fa;">🔐 Security Best Practices</h4>
<ul style="margin: 0; padding-left: 1.5rem; color: #cbd5e1;">
<li>Always sign commits in production repositories</li>
<li>Use credential helpers instead of storing passwords</li>
<li>Enable two-factor authentication on Git hosting platforms</li>
<li>Regularly rotate SSH keys and GPG keys</li>
<li>Use different email addresses for work vs personal repos</li>
<li>Review configuration before working with sensitive repos</li>
</ul>
</div>
Configure a new development machine with production-ready Git settings, aliases, and hooks.
1#!/bin/bash
2# complete-git-setup.sh
3# Run this script to set up Git on a new machine
4
5echo "🚀 Setting up Git configuration..."
6
7# ===== BASIC CONFIGURATION =====
8echo "📝 Configuring user information..."
9git config --global user.name "Your Name"
10git config --global user.email "[email protected]"
11
12echo "🌳 Setting default branch name..."
13git config --global init.defaultBranch main
14
15echo "🎨 Enabling colors..."
16git config --global color.ui auto
17
18echo "✏️ Setting default editor..."
19git config --global core.editor "code --wait"
20
21# ===== ALIASES =====
22echo "⚡ Creating powerful aliases..."
23
24# Basic shortcuts
25git config --global alias.co checkout
26git config --global alias.br branch
27git config --global alias.ci commit
28git config --global alias.st status
29
30# Advanced aliases
31git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
32git config --global alias.last 'log -1 HEAD'
33git config --global alias.undo 'reset HEAD~1 --mixed'
34git config --global alias.amend 'commit --amend --no-edit'
35git config --global alias.ac '!git add -A && git commit'
36git config --global alias.cleanup "!git branch --merged | grep -v '\*\|main\|master' | xargs -n 1 git branch -d"
37git config --global alias.up 'pull --rebase --autostash'
38
39# ===== BEHAVIOR SETTINGS =====
40echo "⚙️ Configuring Git behavior..."
41
42# Pull strategy
43git config --global pull.rebase true
44
45# Auto-prune deleted branches
46git config --global fetch.prune true
47
48# Enable rerere (reuse recorded resolution)
49git config --global rerere.enabled true
50
51# Set merge conflict style
52git config --global merge.conflictstyle diff3
53
54# Show renames in diff
55git config --global diff.renames true
56
57# Colorize moved lines
58git config --global diff.colorMoved default
59
60# Auto-correct typos (1 = 0.1 second delay)
61git config --global help.autocorrect 1
62
63# ===== PERFORMANCE =====
64echo "⚡ Optimizing performance..."
65
66git config --global core.preloadindex true
67git config --global core.fscache true
68git config --global fetch.parallel 0
69
70# ===== SECURITY =====
71echo "🔐 Configuring security settings..."
72
73# Credential caching (1 hour)
74git config --global credential.helper 'cache --timeout=3600'
75
76# Sign commits (uncomment if you have GPG set up)
77# git config --global user.signingkey YOUR_GPG_KEY_ID
78# git config --global commit.gpgsign true
79
80# ===== GLOBAL GITIGNORE =====
81echo "🚫 Creating global gitignore..."
82
83cat > ~/.gitignore_global << EOF
84# OS files
85.DS_Store
86Thumbs.db
87desktop.ini
88
89# Editor files
90.vscode/
91.idea/
92*.swp
93*.swo
94*~
95
96# Environment files
97.env.local
98.env.*.local
99EOF
100
101git config --global core.excludesfile ~/.gitignore_global
102
103# ===== COMMIT TEMPLATE =====
104echo "📋 Creating commit template..."
105
106cat > ~/.gitmessage << EOF
107# Type(scope): Brief description (50 chars)
108
109# Detailed explanation (wrap at 72 chars)
110
111# Footer (issue references, breaking changes)
112EOF
113
114git config --global commit.template ~/.gitmessage
115
116# ===== VERIFICATION =====
117echo ""
118echo "✅ Git configuration complete!"
119echo ""
120echo "📊 Your configuration:"
121git config --global --list
122
123echo ""
124echo "🎯 Useful commands to remember:"
125echo " git lg - Pretty log with graph"
126echo " git last - Show last commit"
127echo " git undo - Undo last commit (keep changes)"
128echo " git amend - Amend last commit"
129echo " git cleanup - Delete merged branches"
130echo " git up - Pull with rebase and autostash"
131echo ""
132echo "🚀 Happy coding!"<p>This script provides a complete Git setup that includes:</p>
<ul>
<li><strong>User Configuration:</strong> Sets name, email, and default branch</li>
<li><strong>Powerful Aliases:</strong> Creates shortcuts for common workflows</li>
<li><strong>Behavior Settings:</strong> Configures pull strategy, rerere, and conflict style</li>
<li><strong>Performance Tuning:</strong> Enables parallel operations and caching</li>
<li><strong>Security:</strong> Sets up credential caching and global gitignore</li>
<li><strong>Commit Template:</strong> Enforces consistent commit messages</li>
</ul>
<p>
Save this as <code>setup-git.sh</code>, make it executable with <code>chmod +x setup-git.sh</code>,
and run it on any new development machine for instant Git productivity.
</p>
Your progress is saved in this browser, on this device only.