JT's Blog

Do the right things and do the things right.

Git Commands

| Comments

本篇並非Git 教學,只是記錄常用的Git 指令,有學到新的指令會再更新上來 如果不太熟悉可在指令後加入 –help 查詢用法

Git 基本設定

查詢設定資訊

1
git config --list

設定全域的使用者與Email (個人使用)

1
2
git config --global user.name <author_name>
git config --global user.email <contact_email_address>

設定區域的使用者與Email (參與計劃或公司專案)

1
2
3
cd local_repo
git config --local user.name <author_name>
git config --local user.email <contact_email_address>

設定別名

1
2
3
4
$ git config --global alias.st status   # git st
$ git config --global alias.ci commit   # git ci
$ git config --global alias.co checkout # git co
$ git config --global alias.br branch   # git br

建立一個全新的Git Repository

1
$ git init --bare project_name.git

本機建立新的repository

1
$ git init

查看工作區(Working Directory)的異動紀錄

1
2
$ git status
$ git st

查看檔案異動差異

1
$ git diff

加入暫存區

1
$ git add <--> <file_path | file_name>

提交並加上註解

1
$ git commit -m <comments>

開啟editor 修改近期已經commit 的註解 (建議少用,除非必要)

1
$ git commit --amend

儲存工作:專案開發到一半,要去別的brach,可使用stash 把修改記錄暫存起來

1
$ git stash

查看暫存的紀錄

1
$ git stash list

取回暫存的紀錄

1
2
3
4
$ git apply

# 取回較舊的暫存紀錄
$ git stash apply stash@{2}

刪除暫存紀錄:apply 只是取回紀錄,但沒有執行刪除的動作

1
$ git stash drop <stash_name>

快速修正前一次 commit 的錯誤,只要修 typo 之後打這行,就會替換掉前一次的 commit-level-operations

1
$ git commit -C HEAD -a –amend

查看提交紀錄

1
$ git log

砍掉commit 重來

1
2
3
$ git reset <--soft | --hard> <-q> <commit>

$ git reset --soft HEAD^ # HEAD^ 表示前一個版本

soft: commit 內容會退回暫存區(staging area),並保留工作區(working directory)

hard: 工作區(working directory) 與暫存區(staging area) 會更新到指定的commit 狀態

Git Branch

列出所有分支且正在使用哪個分支

1
$ git branch

建立新的分支

1
$ git branch <branch_name>

切換分支

1
$ git checkout <branch_name>

建立新的分支並切換到此分支 (等於 git branch + git checkout)

1
$ git checkout -b <branch_name>

修改分支名稱與刪除分支

1
2
$ git branch -m <old_branch_name> <new_branch_name>
$ git branch -d <branch_name>

Git Merge & Git Rebase

觀念:只要 branch 調整完畢,應先將 master merge 至 branch,測試無誤後,在 merge 回 master

merge 分支的功能加master,同時會產生新的HEAD

合併分支到master

1
2
3
4
5
$ git checkout master
$ git merge feature1

# 上下相同
$ git merge master feature1

rebase 是基於某一分支的內容合併,又稱為分支衍合,一樣是合併的動作,但是會銜接著mater 最新的狀態

1
2
$ git checkout <branch]
$ git rebase master

Merge v.s. Rebase

使用時機:如果conflict 較多時,建議使用merge

假設以下例子要做合併,可以看出merge與rebase 有何差異

1
2
3
4
5
maser:  A -> B -> C
branch: D -> E

after rebase: A -> B -> C -> D -> E
after merge:  A -> B -> C -> D -> E -> F

Git Remote

列出當初加入遠端儲存庫時指定的名稱

1
$ git remote

本機加入遠端repository

1
$ git remote add <remote_name> <url>

修改遠端repository url

1
$ git remote set-url <new_remote_name> <url>

拷貝一個已經存在的repository

1
$ git clone <repository_url>

變更遠端簡稱

1
$ git remote rename <old_remote_name> <new_remote_name>

查看remote 資訊

1
$ git remote show <remote_name>

移除遠端repository

1
$ git remote remove <remote_name>

上傳至遠端repository

1
$ git push <remote_name> <branch_name>

合併遠端repository 至本機

1
2
3
4
5
$ git pull <remote_name> <branch_name>

# 上下相同

$ git pull

實用資訊

Reference

Comments