常用git指令总结

189 阅读1分钟

常用的 git 指令

配置 git

git config --global user.name "Your Name" # 设置用户名
git config --global user.email "your@email.com" # 设置邮箱

git 配置有三个级别,优先级从低到高依次为:

  • --system:系统配置,对所有用户起作用,对应的修改会保存在/etc/gitconfig 文件中
  • --global:全局配置,对当前用户起作用,对应配置会保存在 ~/.gitcofnig 或者 ~/.config/git/config 文件中
  • --local:局部配置,只对当前仓库起作用,对应配置会保存在.git/config 文件中

项目初始化

git init          # 初始化一个 Git 仓库
git clone <url>   # 克隆远程仓库

提交代码

git status                 # 查看状态
git add <file>             # 添加到暂存区
git commit -m "message"    # 提交到本地仓库
git add .                  # 添加全部修改

分支管理

git branch                 # 查看本地分支
git branch <name>          # 新建分支
git checkout <name>        # 切换分支
git checkout -b <name>     # 新建并切换分支
git merge <branch>         # 把目标分支合并到当前分支
git branch -d <name>       # 删除分支

远程仓库

git remote -v                     # 查看远程仓库地址
git remote add origin <url>       # 添加远程仓库
git push origin <branch>          # 推送到远程仓库
git pull                          # 拉取最新代码
git fetch                         # 拉取但不合并

查看记录

git log                # 提交历史
git log --oneline      # 简洁模式
git diff               # 查看改动
git show <commit_id>   # 查看某次提交详情

撤销操作

git reset HEAD <file>        # 取消 add 操作
git checkout -- <file>       # 放弃某个文件的改动
git reset --soft HEAD~1      # 撤回最近一次提交(保留改动)
git reset --hard HEAD~1      # 回退并清除改动 (慎用!)