Git 的基本技巧

目的

每次搜尋Git指令並且看過文章後都可以快速記得,但莫名其妙的過一段時間又會回去依賴GUI介面,然而GUI介面用久了常常最根本的指令和標配的-option都會忘光光,所以透過此文紀錄常用的基本Git的指令,讓未來自己想回憶時可以快速進入狀況。

流程

通常Git的使用情境如下

文字描述

情境 : 假設今天專案要開發新的功能並且由我負責,目前整個專案只有兩個branch

master
develop

而討論過後決定新功能的分支要叫做new-feature,所以我的工作流程就會如下面的步驟

  • (checkout) 將目前遠端develop的程式碼拉下來
  • (branch) 建立要完成功能的new-feature分支
  • 撰寫完程式碼
  • (add) 將更改的程式加入Git進行追蹤
  • (commit) 建立Git節點,並且加入到目前的工作區中
  • (pull) 再次將遠端開發分支的程式碼拉下來
  • 如果有衝突則解決衝突,並且回到第四個步驟;如果沒衝突則往下
  • (push) 將節點推到遠端儲存庫中
  • (merge) 將功能分支與開發分支合併

流程圖描述


指令介紹

Checkout

將遠端的分支拉到本地端

git checkout -b <branch-name> origin/<branch-name>

Pull

通常自動設定都會將remote-name設定為origin
pull

git pull [remote-name] <branch-name>

fetch

git fetch [remote-name] <branch-name>

pull與fetch的差別在於,pull會直接將遠端的資料merge進你目前的工作區
簡單來說
pull = fetch + merge

Branch

展示目前branch的情況

git branch -vv

直接讓遠端的branch和本地端branch作連動,連動後以後可以直接輸入git push推出程式碼

git branch -u origin/mybranch

-u為 (參考git官方網站)
-u <upstream>
–set-upstream-to=<upstream>

Set up <branchname>'s tracking information so <upstream> is considered <branchname>'s upstream branch. If no <branchname> is specified, then it defaults to the current branch.

Add

git add <file-name>

同常都是直接將更動的檔案全部add

git add .

Commit

-m為告訴git commit後方為此commit的訊息

git commit -m "message"

Merge

目標branch整合進入現在的工作branch

git merge <target-branch-name>

Push

git push [remote-name] <branch-name>

結論

這篇文章只有節錄一些我常使用的指令,可以說是git的冰山一角都只是一些皮毛,如果有興趣真的推薦去Git官方網站好好看一下每個指令後-option提供的功能

Git官方網站

留言

這個網誌中的熱門文章

Java Lambda Map篇

(InterviewBit) System Design - Design Cache System

設計模式 - 享元模式 (Structural Patterns - Flyweight Design Pattern)