git学习

143 阅读3分钟

分支操作

  • 创建分支 git branch <name>
  • 切换分支 git switch <name>
  • 创建+切换分支 git checkout -b <name> 或者 git switch -c <name>
  • 删除分支 git branch -d <name>
  • 查看分支列表 git branch -v
  • 创建远程分支 git push origin <name>:<name>
  • 删除远程分支 git push origin --delete <name>
  • 合并某分支到当前分支:git merge <name>
  • 将指定的提交(commit)应用于其他分支 git cherry-pick <commit>

版本管理

  • 版本回退 git reset --hard HEAD^ 或者 git reset --hard commit_id 上一个版本就是 HEAD^,上上一个版本就是 HEAD^^往上100个版本可以写成写成HEAD~100

  • 查看最近到最远的提交日志 git log 或者 git log --pretty=oneline

  • 查看所有提交日志 git reflog

  • 撤销修改

    • git checkout -- file 丢弃工作区的修改,使文件回到最近一次git commit或git add时的状态。
    • git checkout <commit> -- file 将指定文件回退到指定提交。
    • git restore --staged <file> 丢弃工作区中的该文件
    • git restore <file> 让这个文件回到最近一次git commit或git add时的状态。
    • git reset HEAD <file> 撤销工作区的修改,将暂存区文件回退到工作区

配置

  • git config --list 显示当前的Git配置
  • git config [--global] user.name "[name]" 设置用户姓名
  • git config [--global] user.email "[email address]" 设置用户邮箱

标签

  • git tag 列出所有标签
  • git tag <tag> 为当前commit创建一个tag
  • git tag <tag> <commit> 为指定commit创建tag
  • git tag -d <tag> 删除本地tag
  • git push <remote> :refs/tags/<tag> 删除远程tag
  • git push <remote> <tag> 提交指定tag到远程
  • git push <remote> --tags 提交所有tag到远程
  • git checkout -b <branch> <tag> 创建一个分支指向指定tag
  • git show <tag> 查看tag 信息

查看信息

  • git status 显示所有变更文件
  • git log --stat 显示commit历史,以及每次commit发生变更的文件
  • git blame <file> 显示指定文件是什么人在什么时间修改过
  • git diff 显示工作区和暂存区的差异
  • git diff --cached <file> 显示暂存区与上一个commit的差异
  • git diff HEAD 显示工作区和当前分支最新commit区别
  • git diff <commit> <commit> 显示两次提交之间的差异
  • ``
  • ``

git stash

  • git stash save '<message>' 将内容存储起来
  • git stash list 查看存储的内容列表
  • git stash pop 恢复内容并删除对应的stash,默认为stash{0},应用并删除其他stash可以使用git stash pop stash@{1}
  • git stash apply stash@{<num>} 恢复内容,但不删除 stash
  • git stash drop stash@{<num>} 删除指定stash
  • git clear stash 清空stash
  • git stash show stash@{<num>} 查看存储内容的改动,,stash@{<num>}可选默认stash@{0}
  • git stash show stash@{<num>} -p 查看存储内容的改动详情,stash@{<num>}可选默认stash@{0}

常用操作

  • 设置账号和邮箱
 git config --global user.name "自已的用户"    例:git config --global user.name "fenlin" 
 git config --global user.email "自己的邮箱"     例:git config --global user.email "wei@163.com"
  • 配置秘钥
ssh-keygen -t rsa -C "your_email@youremail.com"  // 生成秘钥
cd ~/.ssh // 查看秘钥   该目录下的 id_rsa.pub就是要配置到远程的秘钥

常见命令报错

  • git push origin/master

意思是git拒绝合并两个不相干的东西

解决方法

  // 解决冲突
  git fetch origin/master
  git merge
  // 把两段不相干的 分支进行强行合并
  git pull origin master --allow-unrelated-histories
  git push -u origin master -f