mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4mobile wallpaper 5mobile wallpaper 6
737 字
4 分钟
Git常用命令

Git 常用命令#

配置#

  • 设置用户名和邮箱:
git config --global user.name "你的名字"
git config --global user.email "you@example.com"
  • 查看配置:
git config --list

初始化 / 克隆#

  • 初始化仓库:
git init
  • 克隆远程仓库:
git clone https://github.com/user/repo.git

工作区与提交#

  • 查看状态:
git status
  • 添加文件到暂存区:
git add file.txt
git add .
  • 提交更改:
git commit -m "简短说明"
  • 修改最后一次提交(未推送时):
git commit --amend -m "更新说明"
  • 查看差异:
git diff
git diff --staged
  • 从暂存撤回文件:
git restore --staged file.txt

分支管理#

  • 列出分支:
git branch
  • 新建并切换分支:
git checkout -b feature/xxx
# 或
git switch -c feature/xxx
  • 切换分支:
git checkout main
# 或
git switch main
  • 合并分支:
git merge feature/xxx
  • 交互式变基(整理提交):
git rebase -i main
  • 删除分支:
git branch -d feature/xxx
git branch -D feature/xxx # 强制删除

远程仓库#

  • 添加远程:
git remote add origin git@github.com:user/repo.git
  • 推送到远程并建立上游:
git push -u origin main
  • 拉取远程更新(先 fetch 再 merge):
git fetch origin
git merge origin/main
# 或一条命令
git pull
  • 强制推送(谨慎使用):
git push --force-with-lease origin branch-name

注意:强制推送可能覆盖他人的提交,请优先使用 --force-with-lease。


撤销与恢复#

  • 生成一个反向提交(不改历史):
git revert <commit>
  • 重置分支指针(可丢失工作区更改):
git reset --soft <commit> # 保留暂存和工作区
git reset --mixed <commit> # 保留工作区,不保留暂存(默认)
git reset --hard <commit> # 丢弃暂存与工作区改动(危险)
  • 从另一个提交挑选提交:
git cherry-pick <commit>

暂存 (stash)#

  • 暂存当前更改:
git stash save "说明"
# 或
git stash
  • 查看暂存列表:
git stash list
  • 应用并移除最新 stash:
git stash pop
  • 仅应用但保留:
git stash apply stash@{1}

标签与发布#

  • 新建标签并添加注释:
git tag -a v1.0 -m "发布 v1.0"
  • 列出标签:
git tag
  • 推送标签到远程:
git push origin --tags

日志与排查#

  • 简洁图形化日志:
git log --oneline --graph --decorate --all
  • 查看某行最近修改者:
git blame file.txt
  • 查找某次提交引入的问题(二分法):
git bisect start
git bisect bad # 当前版本坏
git bisect good <commit> # 已知好的提交
  • 恢复被删除的分支 / 提交(参考 reflog):
git reflog
git checkout -b recover <ref-from-reflog>

清理与维护#

  • 清理未跟踪文件:
git clean -fd
  • 合并松散对象,回收空间:
git gc --prune=now --aggressive

别名与技巧#

  • 常用别名示例:
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
  • 从历史中彻底移除大文件(使用专用工具):
# 推荐使用 git filter-repo 或 BFG(替代已废弃的 filter-branch)

小贴士:在对公共历史做破坏性变更前(如 filter-repo、强推),先与团队沟通并备份仓库。


常见问题速查#

  • 如何把本地分支与远程分支关联?
git push -u origin my-branch
  • 如何恢复误删的文件?
git checkout -- path/to/file # 退回到 HEAD 的版本
# 或
git restore path/to/file

分享

如果这篇文章对你有帮助,欢迎分享给更多人!

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00