前言
記錄工作上用過的一些 Git 指令,主要是在 terminal (終端機) 或 VScode 的介面操作,沒什麼在用 gitk、SourceTree,覺得在 terminal 輸入看起來也比較厲害 XD
本篇以已會基本 Git 操作為基礎上,進行分享 (需已會 git status
、 git add
、 git commit
、 git branch
、 git checkout
、 git push
、 git pull
等操作)
本篇以此
1 | git clone https://github.com/River-Ye/demo_git.git |
查詢 remote 名稱和 URL
1 | git remote |
超重要小技巧: 可透過 git remote -h
的方式,看有哪些參數,絕大部分指令皆能透過此技巧查詢參數或透過 tldr git remote
的方式看範例
從既有 branch 建立新的 branch 並切到新的 branch
情境: 假如我正在 master,想直接建立新的 branch 並切過去
1 | git checkout -b new_branch_name |
將既有 branch 移動到別的 branch 的位置
情境: 我有一個 river_branch ,想移動到 master branch 的位置
1 | git branch -f <branch_name> <目的地branch_name> |
事情做到一半,突然要切到不同 branch 處理時
很常會遇到的情境,這些指令很常用
1 | # 將手中的事情先藏起來 (非存到 add 或 commit 喔) |
切到遠端 branch
情境: 小菜有將 river_branch 上傳, Louis 要接手處理 (或一同開發)
1 | git pull |
強制覆蓋遠端 branch
1 | git push -f |
備註: 多人協作同 branch 的話,不建議這麼做,會被同事追殺
多人協作同 branch,要 push 時,發現上面有新的 commit 時
每個人開發速度不一樣,有的人比較快,有的會比較慢,
當要 push
發現上面已經有新的 commit 時,可用以下指令
1 | git pull --rebase |
備註: 可能會有 conflict (檔案衝突),與對方確認哪些需保留,Local 解完衝突後,便能 git push
用圖形化方式看 log 資訊
1 | git log --oneline --all --graph |
備註: --oneline
、--all
、--grpah
這三個參數的放置沒有差
示意圖
Local 和 remote 皆增加 tag
假如: remote name 為 origin,default branch 為 master
情境: 將最新 remote 的 master 增加標籤 (tag)
1 | git checkout master |
動作說明:
- 先切到 Local master
- 將最新資料 pull 到 Local
- 在 Local master 增加 tag
- 將 tag 上傳到 remote origin
查看兩個 tag 或 commit 間增加了哪些 pr
1 | git log old_tag_name..new_tag_name --pretty='%s' --reverse |
GitHub repo 設定
範例圖 (Allow merge commits 有無打勾一次看)
查看兩個 commit 間所有檔案的差異 (diff)
1 | git diff commit1..commit2 |
commit 後想反悔 (恢復上一洞)
1 | git reset HEAD^ |
撿別的 commit 過來使用
1 | git cherry-pick commit |
超重要小技巧: 可透過 git cherry-pick -h
的方式,看有哪些參數,絕大部分指令皆能透過此技巧查詢參數或透過 tldr git cherry-pick
的方式看範例
整理自己 branch 的 commit
1 | # rebase 互動模式很好用,網路已有詳細文章可參考 |
一定要知道的
平常不太會用到,需要時,卻很重要的存在
1 | git reflog |
小結
會把一些常用指令設定 alias,像是把 status
設定成 s
、 branch
設定成 b
...等,依照自己常輸入指令設定,可以省下不少時間
多善用 -h
和 tldr
看下有哪些參數、範例,搭配實作,會更快上手喔
參考資料
鐵人賽文章連結:https://ithelp.ithome.com.tw/articles/10238939
medium 文章連結:https://link.medium.com/Mmx5PSNfR9
本文同步發布於 小菜的 Blog https://riverye.com/
備註:之後文章修改更新,以個人部落格為主