Git 是一個被廣泛使用的 版本控制系統(Version Control Systems),雖然現在有許多圖形化的介面可以使用,但要完全發揮 Git 的各個功能細節,使用 Command 進行操作依舊是相當重要的。
本文重新整理了當初在學習 Git 時所寫的筆記,並另外加入一些新的補充,紀錄了大部分 Git 中常用的 Commit、Branch、Remote 相關指令,做為學習的參考或使用上的備忘錄。
關於 Commit
在 Git 中,可以自由決定你要進行追蹤 (track) 與版本控制的檔案,並在希望留下紀錄點時使用 Commit 指令來留下紀錄節點。
#檢查專案狀態 git status #添加新的檔案追蹤 (紀錄 new 跟 modified) #加上 -u 會紀錄 new、modified 以及 deleted git add <file> git add -u <file> #移除檔案的追蹤並刪除檔案 (紀錄 deleted) git rm <file> #移除檔案的追蹤並保留檔案 (紀錄 deleted) git rm --cached <file> #記錄所有資料夾中不被 ignore 的變化,需慎用 git add . #增加commit節點,並留下描述 #加上 -a 會自動紀錄所有 modified 跟 deleted git commit -m <message> git commit -am <message> #取消最後一個commit git reset --soft HEAD^ #強制恢復到先前commit的版本 git reset --hard HEAD git reset --hard HEAD^ git reset --hard HEAD~2 #回復特定檔案至特定版本 git checkout HEAD^ <file>
關於 Branch
在很多情境下,會希望同時有多種版本的專案同時開發,可能是為了尚未確定的新功能,或者希望多人合作時不要互相干擾。Branch 指令可以滿足你的需求,但同時也要確實清楚自己的每個操作所代表的意義,以免專案內容大亂。
#顯示所有分支,目前所處在的分支前方會有個 * git branch #移動到特定的分支進行工作,若有任何尚未 commit 的變動將會無法移動 git checkout <branch_name> #由 <branch_name_origin> 建立新分支 <branch_name>,但不移動 git branch <branch_name> <branch_name_origin> #建立新的分支,同時移動到新分支進行工作 git checkout -b <branch_name> <branch_name_origin> #合併 <branch_name> 分支到 <branch_name_target> 之上 #千萬要注意必須先 checkout 至要合併的目標分支 #而 --no-ff 模式會保留被合併分支的 commit,並增加一個 merge commit git checkout <branch_name_target> git merge --no-ff <branch_name> #刪除分支 git branch -d <branch_name>
關於 Remote
Remote 是將 Git 的共享能力加以發揮的重要功能,不論是為了在不同設備上進行開發,與人分享專案跟合作,甚至是為了自動部屬,都是 Remote 功能的應用。
#顯示所有的 Remote git remote -v #增加一個 Remote git remote add <remotename> <url> #使用 <branch_name> 作為遠端 Branch 的複製 git branch -f <branch_name> <shortname>/<remote_branch_name> #將工作位置移動至與遠端連結的 Branch,並更新至遠端最新的 Commit git checkout <branch_name> git pull #上傳本地 Commit 紀錄至遠端 git push #上傳本地 Commit 紀錄至遠端,若無此遠端 Branch 則同時建立一個新的遠端 Branch #加上 -u 會將本地 Branch<branch_name> 設為遠端 Branch<remote_branch_name> 的複製 #未來才能直接使用 pull/push git checkout <branch_name> git push -u <remotename> <remote_branch_name> #將所有本地 Branch 推送至遠端,慎用 git push --all #刪除遠端 Branch git push <remotename> :<remote_branch_name>
其他
- 或許你想知道為何別人的指令長的跟你不大一樣,似乎簡短了一些?下方有指令說明。
- 如果你新增了 .gitignore,卻發現有些檔案早先已經不小心加入追蹤了,希望移除追蹤但不移除檔案?下方有指令說明。
#設定指令縮寫: git config --global alias.st status git config --global alias.ci commit git config --global alias.co checkout git config --global alias.br branch #確認某檔案是否有被追蹤 git ls-files | grep <filename> #遺忘到所有追蹤對象,可用於重新採用 .gitignore 檔設定 git rm -rf --cached . #遺忘所有已經追蹤,但應當被忽略的檔案 git ls-files -c -i --exclude-standard | xargs git rm --cached
- 如果已經開始使用 Branch 做為團隊合作的利器,那可以研究一下 git-flow 這套 Git branching model,了解一個善用 Branch 的例子。文章尾端附有參考連結。
Git 不只是為一個備份專案的工具,了解 Branch、Remote、Submodule 等更多功能後,方能體會版本控制為開發帶來的強大效果。
參考
- Git – Reference – https://git-scm.com/docs
- A successful Git branching model – http://nvie.com/posts/a-successful-git-branching-model/
- Git flow 開發流程 – https://ihower.tw/blog/archives/5140