1. 程式人生 > >最常用的Git命令

最常用的Git命令

版本管理,多人協作

  • 檢視遠端庫資訊
git remote
git reomte -v //顯示更詳細的資訊
  • 刪除本地的遠端庫
git remote rm origin
  • 推送分支
git push origin <branchname>
  • 抓取遠端分支的新提交
git pull
  • 關聯本地分支和遠端分支
git branch --set-upstream branch-name origin/branch-name 
//遠端分支和本地的名稱最好一樣

版本回退

  • 檢視提交log

git log

可以用--pretty=oneline 引數來格式化

  • 回退到上一個版本,HEAD代表上一個版本,如果是上100個話就是HEAD~100

git reset --hard HEAD^

  • 回到指定的某個版本

git reset --hard <版本號>

  • 顯示每一次命令,可以用來找到版本號,從而回到任意一個版本

git reflog

撤銷修改

  • 把filename檔案的修改撤銷,就是讓這個檔案回到最近一次git commitgit add時的狀態

git checkout -- <filename>

  • 撤銷暫存區的修改,重新放回工作區

git reset HEAD <filename>

刪除檔案

  • 從版本庫中刪除檔案
git rm <filename> //從暫存區刪除
git commit -m "remove filename"
  • 刪錯了,從版本庫中把檔案恢復到最新版本
git checkout HEAD -- <filename>
或
git checkout HEAD <filename>

遠端倉庫

  • 關聯遠端倉庫
git remote add origin 
[email protected]
:username/repo-name.git
  • 將本地庫推送到遠端庫,
git push -u origin master//第一次推送
//由於遠端庫是空的,我們第一次推送master分支時,
//加上了-u引數,Git不但會把本地的master分支內容推送的遠端新的master分支,
//還會把本地的master分支和遠端的master分支關聯起來,
//在以後的推送或者拉取時就可以簡化命令

git push origin master //推送
  • 克隆遠端倉庫
git clone [email protected]-name:username/repo-name.git

git clone url-address

分支管理

  • 建立新分支
git checkout -b <branchname>//加上 -b 引數代表建立並切換
//相當於下列兩條命令
git branch <branchname>
git checkout <branchname>
  • 檢視當前分支
git branch
//git branch 命令會列出所有分支,當前分支前面會打*號

git branch -a //檢視所有分支
  • 合併分支
git merge <branchname>//用於合併指定分支到當前分支
  • 刪除分支
git branch -d <branchname>
  • 檢視分支合併情況(分支合併圖)
git log --graph //使用此命令檢視合併圖

//示例
git log --graph --pretty=oneline --abbrev-commit
//結果示例如下
*   59bc1cb conflict fixed
|\
| * 75a857c AND simple
* | 400b400 & simple
|/
* fec145a branch test
...
  • 使用 –no-ff 引數禁用 Fast forward
git merge --no-ff -m "merge with no-ff" <branchname>
//因為本次合併要建立一個新的commit,所以加上-m引數,把commit描述寫進去
  • bug分支,隱藏工作區間
git stash //把當前工作區間隱藏

git stash list //檢視stash列表

git stash apply <[email protected]{0}> //恢復stash,但stash並不刪除,可通過git stash drop 刪除

git stash drop //刪除stash

git stash pop //恢復stash並刪除stash
  • 強行刪除為合併分支
git branch -D <branchname> //不要輕易使用

遠端分支

  • 新建遠端分支
git push origin branch-name:branch-name 
//將本地分支推送給遠端,一般遠端分支和本地分支名稱一樣
  • 刪除遠端分支
//推送一個空分支給遠端,相當於刪除
git push origin :branch-name 

//刪除遠端分支
git push origin --delete branch-name

標籤管理

  • 建立和檢視標籤
git tag //檢視所有標籤

git tag <tag-name> //打一個新標籤,預設是HEAD

git tag <tag-name> <commit-id> //為指定的commit-id打標籤

git show <tag-name> // 檢視標籤資訊
  • 操作標籤
git tag -d <tag-name> //刪除標籤

git push origin <tag-name> //推送標籤到遠端

git push origin --tags //推送所有標籤到遠端
  • 刪除遠端標籤
git tag -d <tag-name> //需要先刪除本地標籤

git push origin :refs/tags/tag-name //然後把標籤推送到遠端

參考文章