常用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 [email protected]:lilingyu/pthread_test.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to '[email protected]: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