常用git操作
- 查看分支:
git branch
,*指示当前所处分支 - 新建分支并切换到新分支:
git checkout -b branchname
- 切换到某分支:
git checkout somebranch
- 删除分支:
git branch -d deletebranch
- 查看当前状态:
git status
红色警告部分会提示你某些文件已经修改,但还没添加到索引库,如果直接提交commit会报错,因为commit时只能从已经添加到索引库的文件中提交,所以需要用git add -u
添加修改的文件 - 提交:
git commit -m "your comment"
,如果有红色警告部分 - 查看提交记录:
git log
- 查看已经修改但未提交的代码:
git diff
- 远程信息:
git remote -v
- 从远程拉代码,更新本地代码:
git pull
- 从本地上传代码,更新远程:
git push origin localbranch
用local - 版本回退:
git reset HEAD^
回退到上一个版本,HEAD^^回退到上上个版本 - git配置,用户名和邮箱:~/.gitconfig
- 修改上一次提交,可以提交最新修改,更新提交日志:
git commit --amend
- 舍弃未提交的修改
git checkout --your.file
案例1
在主分支develop上做了修改,需要将所做的修改变为一个分支branch1,然后将这个分支提交,上传,具体步骤如下:
- 创建新分支:
git checkout -b branch1
- 将更新文件添加到索引库:
git add -u
- 提交:
git commit -m "your comment"
- 上传:
git push origin branch1
案例2
如何将本地代码上传至远端?
通常我们可以从远端用git clone
将代码考下来,修改后可以方便提交,push。但有的时候自己在本地写了代码,建了git,而远端并没有这个项目,将本地代码上传还需要一些步骤。
添加远端
git remote add origin git@github.com:yourname/yourproject.git
远端分支和本地分支建立连接
git branch --set-upstream-to=origin/master master
上传:
git push origin master
如果没有步骤2,直接push 会报错:
LiLingyudeMacBook-Pro:test lilingyu1$ git push origin master
To 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 behind
hint: 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 pull
From github.com:lilingyu/pthread_test
* [new branch] master -> origin/master
There 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
案例三
合并多个提交:
有两个新的提交,发现这两个提交都是解决同一个问题,并没有必要分两次提交,需要合并
- 查看提交历史:
git log
回退到这两个提交之前的一个版本:
git rebase -i 0d13734bf89161b557dcb7db8b608ba5993b6a01
会跳出一个打开的文本编辑,保存的版本前面加pick,合并的版本前加s,参考:强制上传:
git push origin localbranch -f
- 4.
案例4
上传github代码
新建项目并上传
echo "# didi1" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin git@github.com:username/repo.git
git push -u origin master
已有项目上传
git remote add origin git@github.com:username/repo.git
git push -u origin master