常用git操作备忘

常用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 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

案例三

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

  1. 查看提交历史:

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

    git rebase -i 0d13734bf89161b557dcb7db8b608ba5993b6a01

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

  3. 强制上传:

    git push origin localbranch -f
  4. 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值