2017-04-21 53 views
10

我想要做的是版本檢查。我想確保代碼保持在最低版本之上。所以我需要一種方法來知道當前分支是否包含指定的提交。給定一個提交ID,如何確定當前分支是否包含提交?

+3

的可能的複製[如何列出包含給定提交的分支?](http://stackoverflow.com/問題/ 1419623/how-to-list-branches-that-c​​ontain-a-given-commit) – kowsky

+0

請參閱建議的副本以瞭解如何查找包含指定提交的* all *分支。要確定* current *分支是否包含commit * C *,請使用「plumbing」命令'git merge-base --is-ancestor'。當前分支包含* C *,如果* C *是HEAD的祖先,那麼:'如果git merge-base --is-ancestor $ hash HEAD;然後回聲我包含提交$哈希;其他回聲我不包含提交$散列; fi' – torek

+0

嗨,請提交這個答案,以便它可以被選爲正確答案=) – Ben

回答

6

有多種方式如何做到這一點,但您可以使用git log,然後搜索特定提交採用grep作爲最簡單的選擇,但不總是精確。

git log | grep <commit_id> 

另一種選擇是使用以下方法來獲取truefalse答案

if [ 0 -eq $(git branch $(git rev-parse --abbrev-ref HEAD) --contains <<<commit_id>>> > /dev/null 2> /dev/null; echo $?) ]; then echo "true"; else echo "false"; fi 
+2

與分支名稱完全匹配更新了答案。如果'git log'出於其他原因提及了提交SHA,'grep'可能會導致誤報,例如,它在提交消息中被提到是來自另一個分支的端口的結果。 –

+1

更正(或者添加另一個選項)。 – JiriS

+0

請參閱使用內置git工具集的問題的評論。 https://stackoverflow.com/questions/43535132/given-a-commit-id-how-to-determine-if-current-branch-contains-the-commit/43535152#comment74126598_43535132 – Ben

16

獲取包含特定提交的分支的列表。

$ git branch --contains <commit-id> # get all the branches where the commit exists 

檢查分支是否具有特定的提交。

$ git branch --contains <commit-id> | grep <branch-name> # output the branch-name if the commit exists in that branch 

編輯:搜索與精確匹配的分支(比如,feature)。

$ git branch --contains <commit-id> | grep -E '(^|\s)feature$' 

例如,如果你有3個分支叫featurefeature1feature2然後

$ git branch --contains <commit-id> | grep 'feature' 

feature 
feature1 
feature2 

$ git branch --contains <commit-id> | grep -E '(^|\s)feature$' 

feature  
+0

這裏的'grep'也可能導致錯誤的肯定,如果有其他分支包含提交的名稱也包含''作爲子串。 –

+1

是@AdamSpiers,用'grep -E'(^ | \ s)branchname $''' –

相關問題