在git中,“push -u”的意思是將本地的分支版本上傳到遠程合并,并且記錄push到遠程分支的默認值;當添加“-u”參數時,表示下次繼續push的這個遠端分支的時候推送命令就可以簡寫成“git push”。
本文操作環境:Windows10系統、Git2.30.0版、Dell G3電腦。
git中push -u是什么意思
git push?命令用于從將本地的分支版本上傳到遠程并合并。
一般將本地倉庫推送到遠程倉庫的時候一般會使用 git push 命令。而作為新手,在網上看到一些教程有的會在 git push 的時候帶上一個 -u 參數,而有的則沒有。而推送的實際結果沒有什么區別。就很好奇 -u 參數的作用到底是什么?
搜索了一番,綜合了一些大家的說明和解析,總結記錄一下。
參數解析:
首先對于 git push,有這樣一段描述:
-u
–set-upstream
for every branch that is up to date or successfully pushed, add upstream (tracking) reference, used by argument-less git-pull(1) and other commands. For more information, see branch.
.merge in git-config(1).
在這個描述中,可以看到 -u 參數與下面這個變量相關
branch.
branch.
而upstream是指其他人將從中獲取的主要存儲庫,例如您的github存儲庫。-u選項自動為您設置上游,將您的倉庫鏈接到一個中央倉庫。這樣,將來Git會“知道”您要推送到的位置以及您要從哪里提取的信息,因此您可以使用git pull或git push不使用參數。?
當您git pull從分支進行操作而未指定源遠程或分支時,git會查看 branch.
至此,簡單來說,帶上-u 參數其實就相當于記錄了push到遠端分支的默認值,這樣當下次我們還想要繼續push的這個遠端分支的時候推送命令就可以簡寫成git push即可。
示例展示:
下面展示一個示例來說明這一點。
andy@AndyMacBookPro:/usr/local/github/andy/php-examples$?git?pull 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>?test</branch></branch></remote>
這個就是如果你之前未使用 -u 參數,后面省略了想要pull的分支參數而產生的結果。pull 因為沒有track for the current branch. 所以他不知道你要從哪里pull,所以這也就是 -u 參數的意義,指定trach branch。
其實你可以在指定完-u之后,去.git/config看GIT配置文件,可以看到下面有了branch “test”的分支的記錄:
[branch?"master"]? ?remote?=?origin merge?=?refs/heads/master? [branch?"test"] remote?=?origin merge?=?refs/heads/test
這樣git才能知道當前test下的remote和merge的信息,如果你在git push的時候沒有帶入-u參數,那么config中就不會有branch “test”這一項。
?[branch?"master"] ????remote?=?origin ????merge?=?refs/heads/master
配置說明,這告訴Git 2件事:
當您在master分支上時,默認的遙控器是origin。
在git pullmaster分支上使用時(未指定任何遠程和分支),請使用默認的remote(源)并合并來自remote master分支的更改。
配置修改
您可以手動去.git/config修改GIT配置文件內容,也可以使用命令行設置這些選項。
?$?git?config?branch.master.remote?origin ?$?git?config?branch.master.merge?refs/heads/master
如果使用命令進行配置,它將有一定的糾錯能力。比如您鍵入了一個不存在的分支或者您沒有執行git remote add 操作。在較新的git中,希望您使用 git branch –set-upstream-to=origin/master master
其實,執行添加了-u 參數的命令 git push -u origin master就相當于是執行了
git push origin master 和
git branch –set-upstream master origin/master。
所以,在進行推送代碼到遠端分支,且之后希望持續向該遠程分支推送,則可以在推送命令中添加 -u 參數,簡化之后的推送命令輸入。
推薦學習:《Git教程》