Git常用命令

配置

  • 设置用户名和邮箱
    git config –global user.name “Your Name”
    git config –global user.email “[email protected]
  • 查看当前配置编辑git config --list

初始化与克隆

  • 初始化一个新的 Git 仓库编辑git init
  • 克隆一个远程仓库编辑git clone <repository-url>

查看状态与日志

  • 查看当前工作目录的状态编辑git status
  • 查看提交日志编辑git log
  • 查看日志简洁版本编辑git log --oneline

工作区与暂存区

  • 将文件添加到暂存区编辑git add <file>
  • 添加所有文件到暂存区编辑git add .
  • 从暂存区移除文件编辑git reset <file>
  • 提交修改到本地仓库编辑git commit -m "Your commit message"

分支操作

  • 创建一个新分支编辑git branch <branch-name>
  • 查看所有分支编辑git branch
  • 切换到指定分支编辑git checkout <branch-name>
  • 创建并切换到新分支编辑git checkout -b <branch-name>
  • 删除本地分支编辑git branch -d <branch-name>

合并与变基

  • 合并分支编辑git merge <branch-name>
  • 变基当前分支到指定分支编辑git rebase <branch-name>

远程操作

  • 查看远程仓库编辑git remote -v
  • 添加远程仓库编辑git remote add origin <repository-url>
  • 从远程仓库拉取代码编辑git pull origin <branch-name>
  • 推送代码到远程仓库编辑git push origin <branch-name>
  • 删除远程分支编辑git push origin --delete <branch-name>

其他常用命令

  • 查看当前目录的 git 信息编辑git status
  • 放弃工作目录中的所有修改编辑git checkout -- <file>
  • 放弃暂存区的更改编辑git reset HEAD <file>
  • 查看当前 HEAD 所在的 commit编辑git show
  • 创建一个标签编辑git tag <tag-name>
  • 删除本地标签编辑git tag -d <tag-name>
  • 推送标签到远程编辑git push origin <tag-name>
  • 列出所有标签编辑git tag

分支比较与冲突解决

  • 查看不同分支之间的差异编辑git diff <branch1> <branch2>
  • 合并时处理冲突编辑git mergetool
  • 合并后标记解决冲突编辑git add <file>
  • 完成合并编辑git commit

其他高级操作

  • 创建一个新的提交(不需要修改文件)编辑git commit --allow-empty -m "Empty commit"
  • 查看文件修改的历史编辑git blame <file>
  • 暂时保存修改(Stash)编辑git stash
  • 查看 stash 列表编辑git stash list
  • 恢复 stash 修改编辑git stash apply
  • 删除 stash 修改编辑git stash drop
  • 还原一个提交编辑git revert <commit-hash>