常用git操作备忘

来源:互联网 发布:淘宝恒天然wpc80分装 编辑:程序博客网 时间:2024/05/21 07:35

常用git操作

  1. 查看分支:git branch,*指示当前所处分支
  2. 新建分支并切换到新分支:git checkout -b branchname
  3. 切换到某分支:git checkout somebranch
  4. 删除分支:git branch -d deletebranch
  5. 查看当前状态:git status红色警告部分会提示你某些文件已经修改,但还没添加到索引库,如果直接提交commit会报错,因为commit时只能从已经添加到索引库的文件中提交,所以需要用git add -u添加修改的文件
  6. 提交:git commit -m "your comment",如果有红色警告部分
  7. 查看提交记录:git log
  8. 查看已经修改但未提交的代码:git diff
  9. 远程信息:git remote -v
  10. 从远程拉代码,更新本地代码:git pull
  11. 从本地上传代码,更新远程:git push origin localbranch用local
  12. 版本回退:git reset HEAD^回退到上一个版本,HEAD^^回退到上上个版本
  13. git配置,用户名和邮箱:~/.gitconfig
  14. 修改上一次提交,可以提交最新修改,更新提交日志:git commit --amend
  15. 舍弃未提交的修改git checkout --your.file

案例1

在主分支develop上做了修改,需要将所做的修改变为一个分支branch1,然后将这个分支提交,上传,具体步骤如下:

  1. 创建新分支:git checkout -b branch1
  2. 将更新文件添加到索引库:git add -u
  3. 提交:git commit -m "your comment"
  4. 上传:git push origin branch1

案例2

如何将本地代码上传至远端?
通常我们可以从远端用git clone将代码考下来,修改后可以方便提交,push。但有的时候自己在本地写了代码,建了git,而远端并没有这个项目,将本地代码上传还需要一些步骤。

  1. 添加远端

    git remote add origin git@github.com:yourname/yourproject.git
  2. 远端分支和本地分支建立连接
    git branch --set-upstream-to=origin/master master

  3. 上传:git push origin master
    如果没有步骤2,直接push 会报错:

LiLingyudeMacBook-Pro:test lilingyu1$ git push origin masterTo git@github.com:lilingyu/pthread_test.git ! [rejected]        master -> master (non-fast-forward)error: failed to push some refs to 'git@github.com:lilingyu/pthread_test.git'hint: Updates were rejected because the tip of your current branch is behindhint: its remote counterpart. Integrate the remote changes (e.g.hint: 'git pull ...') before pushing again.hint: See the 'Note about fast-forwards' in 'git push --help' for details.LiLingyudeMacBook-Pro:test lilingyu1$ git pullFrom github.com:lilingyu/pthread_test * [new branch]      master     -> origin/masterThere is no tracking information for the current branch.Please specify which branch you want to merge with.See git-pull(1) for details    git pull <remote> <branch>If you wish to set tracking information for this branch you can do so with:    git branch --set-upstream-to=origin/<branch> master

案例三

合并多个提交:
有两个新的提交,发现这两个提交都是解决同一个问题,并没有必要分两次提交,需要合并

  1. 查看提交历史:

    git log
  2. 回退到这两个提交之前的一个版本:

    git rebase -i 0d13734bf89161b557dcb7db8b608ba5993b6a01

    会跳出一个打开的文本编辑,保存的版本前面加pick,合并的版本前加s,参考:

  3. 强制上传:

    git push origin localbranch -f
  4. 4.

案例4

上传github代码

新建项目并上传

echo "# didi1" >> README.mdgit initgit add README.mdgit commit -m "first commit"git remote add origin git@github.com:username/repo.gitgit push -u origin master

已有项目上传

git remote add origin git@github.com:username/repo.gitgit push -u origin master
0 0
原创粉丝点击