Basic add/commit/push handles daily collaboration. Advanced commands give precise history control and efficient debugging.
Interactive Rebase for Clean History
Use reword/squash/fixup/drop directives to rewrite sequences: merge WIP commits, fix messages, remove debug code, keep main branch history clean.
#!/usr/bin/env bash
set -euo pipefail
# 1. Interactive Rebase: squash最近5条WIP,reword命名
git rebase -i HEAD~5 <<EOF
pick a1b2c3d feat: add login API
reword b3e4f5g fix typo in user model
squash c6h7i8j wip: add test cases
fixup d9k0l1m fix lint issues
drop e2n3o4p tmp debug log
EOF
# 2. Cherry-pick: 跨分支移植hotfix
git checkout release/2.0
git cherry-pick -x a1b2c3d
# 多个提交合入暂存区手动合并后一次性提交:
# git cherry-pick --no-commit b3e4f5g c6h7i8j
# git cherry-pick --continue / --abort
# 3. Bisect: 二分找引入Bug的提交
git bisect start
git bisect bad HEAD
git bisect good v1.8.0
git bisect run pytest tests/test_auth.py -x
# Output: a1b2c3d is the first bad commit
git bisect reset
# 4. Reflog救援
git reflog --date=iso | head -20
# git reset --hard HEAD@{3}
# 5. 批量修复作者信息
git filter-branch -f --env-filter '
if [ "$GIT_AUTHOR_EMAIL" = "old@example.com" ]; then
export GIT_AUTHOR_NAME="Correct Name" GIT_AUTHOR_EMAIL="new@example.com"
export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME" GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"
fi
' HEAD
Bisect for Binary-Search Bug Hunting
When regression appeared mysteriously, Bisect binary-searches the first bad commit. Combined with test scripts it finds the issue in minutes with zero manual effort.
| Command | Purpose | Risk Level | Best For |
|---|---|---|---|
| rebase -i | Rewrite history | Medium (local only) | Before merge request |
| cherry-pick | Port commits | Low (new hashes) | Backport hotfixes |
| bisect | Binary search | Very Low (read-only) | Regression hunting |
| reflog | Op history | Zero (read-only) | Disaster recovery |
| filter-branch | Bulk rewrite | Very High (hash change) | Author info fixes |
Best Practices
Golden rule: never rebase pushed commits. Before destructive ops, tag safety net with git tag backup-$(date +%Y%m%d).