Appearance
一句话结论
掌握常用 Git 命令可以大幅提高开发效率。
基础操作
提交代码
bash
# 查看状态
git status
# 添加所有更改
git add .
# 添加特定文件
git add src/components/Button.vue
# 提交
git commit -m "feat: 添加新功能"
# 提交并添加描述
git commit -m "feat: 添加新功能" -m "详细描述信息"分支操作
bash
# 创建并切换到新分支
git checkout -b feature/new-feature
# 或者使用新语法
git switch -c feature/new-feature
# 查看所有分支
git branch -a
# 删除分支
git branch -d feature/old-feature
# 强制删除分支
git branch -D feature/old-feature高级技巧
修改提交历史
bash
# 修改最后一次提交
git commit --amend -m "新的提交信息"
# 修改最后一次提交并添加文件
git add forgotten-file.js
git commit --amend --no-edit
# 交互式 rebase(修改最近 3 次提交)
git rebase -i HEAD~3暂存更改
bash
# 暂存当前更改
git stash
# 暂存并添加描述
git stash save "正在开发的功能"
# 查看所有暂存
git stash list
# 应用最近的暂存
git stash apply
# 应用并删除暂存
git stash pop
# 删除特定暂存
git stash drop stash@{0}查看历史
bash
# 查看提交历史
git log
# 单行显示
git log --oneline
# 图形化显示
git log --graph --oneline --all
# 查看特定文件的更改历史
git log -p src/components/Button.vue
# 查看谁修改了文件
git blame src/components/Button.vue实用脚本
快速提交脚本
bash
#!/bin/bash
# quick-commit.sh
if [ -z "$1" ]; then
echo "请提供提交信息"
exit 1
fi
git add .
git commit -m "$1"
git push清理分支脚本
bash
#!/bin/bash
# cleanup-branches.sh
# 删除已合并的本地分支
git branch --merged | grep -v "\*\|main\|master\|develop" | xargs -n 1 git branch -d
# 清理远程已删除的分支引用
git remote prune origin配置别名
bash
# 添加到 ~/.gitconfig
[alias]
st = status
co = checkout
br = branch
ci = commit
unstage = reset HEAD --
last = log -1 HEAD
visual = !gitk
lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit可复用的要点
- 使用有意义的提交信息(遵循 Conventional Commits)
- 经常提交,保持提交粒度小
- 使用分支进行功能开发
- 定期清理不需要的分支
- 配置 Git 别名提高效率