Git命令笔记

日常使用Git时经常记不住相关操作,故将常用的命令记录以便翻查

基本操作

  • git init 初始化仓库
  • git clone [url] 克隆远程仓库到本地
  • git add [file] 添加指定文件到缓存区
  • git add . 添加所有文件到缓存区
  • git status 查看仓库当前状态
  • git diff 对比缓存器与工作区的差异
  • git pull [remote] [branch] 拉取远程仓库, 并与本地分支合并
  • git push [remote] [branch] 推送本地指定分支到远程仓库
  • git push [remote] --force 强制推送当前分支到远程仓库
  • git push [remote] --all 推送所有分支到远程仓库
  • git commit -m [message] 将缓存区内容提交到仓库
  • git reset HEAD 还原工作区与缓存区到上一次提交状态
  • git reset [file] 还原缓存区中指定文件, 工作区不变
  • git rm 删除仓库中指定文件
  • git mv 移动/重命名仓库中的文件

分支

  • git branch 列出所有本地分支
  • git branch -r 列出所有远程分支
  • git branch -a 列出所有本地和远程分支
  • git branch [branch-name] 新建分支
  • git checkout -b [branch-name] 新建并切换分支
  • git checkout [branch-name] 切换分支
  • git merge [branch-name] 合并指定分支到当前分支
  • git branch -d [branch-name] 删除分支

日志

  • git log 显示当前分支的提交历史
  • git log --stat 显示每次提交的变更
  • git log -S [keyword] 根据关键词搜索提交历史

远程仓库

  • git remote add [name] [url] 新建远程仓库
  • git remote -v 显示所有远程仓库信息
  • git remote show [name] 显示指定远程仓库信息

还原

  • git checkout [file] 还原缓存区指定文件到工作区
  • git checkout [commit] [file] 还原指定commit的指定文件到缓存区和工作区
  • git checkout . 还原缓存区所有文件到工作区
  • git reset --hard 还原缓存区和工作区与上一次commit一致
  • git reset [commit] 当前分支HEAD变为指定commit, 同时重置缓存区, 但工作区不变
  • git reset --hard [commit] 当前分支HEAD变为指定commit, 同时重置缓存区和工作区
  • get reset --keep [commit] 重置当前分支HEAD为指定commit, 但缓存区和工作区都保持不变

常用组合命令

  • 新建远程仓库连接origin,并首次推送

    1
    2
    git remote add origin git@github:xxx/xxx.git
    git push -u origin -all
  • 强制pull远程仓库覆盖本地文件

    1
    2
    3
    git fetch --all
    git reset --hard origin/master
    git pull