Git 秘訣筆記

Posted on  Apr 14, 2016  in  Git 版本控制  by  Amo Chen  ‐ 2 min read

我是 Git, GitHub 的重度使用者,可以說是吃飯用的工具。就在這邊整理一些 Git 的筆記。

打開 git 的指令自動訂正功能

$ git config --global help.autocorrect 1

Fetch GitHub 上的 PR(Pull Request)

假設有個人發佈一個 Pull Request ,那麼除了開一個分支去 pull 他的分支之外,還可以用 fetch 的方式把 PR 抓回來,這種方式會直接在 local 開一個相對應的分支名稱,再 checkout 過去就好。

指令:

$ git fetch origin pull/<pull_request_id>/head:<branch_name>
$ git checkout <branch_name>

例如有個人的 Pull Request ID 是 3, 分支名稱是 merge_me ,指令就會長這樣:

$ git checkout -b merge_me
$ git fetch origin pull/3/head:merge_me

此外, Git 的文件也有提到可以用 –track 跟遠端分支同步

$ git checkout -b <branch> --track <remote>/<branch>

p.s. branch 名稱要相同

例如:

$ git checkout -b merge_me --track origin/merge_me

Mirror local repository to remote

除了將 branch 一個一個 push 到 remote repository 之外,其實還可以在 repository 中設定 mirror ,這個 mirror 就會將本地端(local)的所有 branch 一起 mirror 到 remote repository 。

指令:

$ git remote add backup your_server:/path/to/backup/repo
$ git push --mirror backup

or

$ git config alias.backup "push --mirror backup" # 設定 alias
$ git backup

p.s. 記得在 remote 先建好 git repository

例如:

$ git remote add backup 123.123.123.123:/home/user/mirror_repo
$ git push --mirror backup

搜尋含有特定關鍵字的相關 commit (包含 diff)

有時候想搜尋哪些 commit 中對特定行做了修改,可以利用 git log -S 指定關鍵字來進行搜尋。

指令:

$ git log -c -S'your_keyword'

p.s. -c 代表顯示 commit 的 diff

p.s. 也有 -G 正規表示式的用法!

刪除 remote branch

$ git push origin :remote-branch-name

或者

$ git push origin --delete remote-branch-name

強制將行尾的空格視為 error ,避免 commit 行尾的空格

$ git config --global core.whitespace trailing-space

p.s. 還有 space-before-tab , blank-at-eof 等參數可使用,詳見 man git-diff

設定 global 的 gitignore

$ git config --global core.excludesfile '~/.gitignore'

切換回最近一次使用的 branch

用途跟 cd - 很像, git 也有類似的用法:

$ git checkout -

查看已經 merge 哪些分支

$ git branch --merged
* master
  feature1
  feature2

上述代表 master 已經合併了 feature1, feature2 2 個分支。

從某個 branch 直接複製檔案

以下指令可以複製某個 branch 上的檔案而不需切換分支。

$ git checkout <the_branch> -- <file_path>

以 word 為單位顯示 diff

在編修文字段落時,可以使用 --word-diff 用 word 為單位進行 diff 。避免以 line 為單位看不出何處變動。

$ git diff --word-diff

查看 contributors & number of commits

$ git shortlog -sn

將某個檔案回復到某個時間點/commit

$ git checkout v1.2.3 -- file         # tag v1.2.3
$ git checkout stable -- file         # stable branch
$ git checkout origin/master -- file  # upstream master
$ git checkout HEAD -- file           # the version from the most recent commit
$ git checkout HEAD^ -- file          # the version before the most recent commit

對抗久坐職業傷害

研究指出每天增加 2 小時坐著的時間,會增加大腸癌、心臟疾病、肺癌的風險,也造成肩頸、腰背疼痛等常見問題。

然而對抗這些問題,卻只需要工作時定期休息跟伸展身體即可!

你想輕鬆改變現狀嗎?試試看我們的 PomodoRoll 番茄鐘吧! PomodoRoll 番茄鐘會根據你所設定的專注時間,定期建議你 1 項辦公族適用的伸展運動,幫助你打敗久坐所帶來的傷害!

追蹤新知

看完這篇文章了嗎?還意猶未盡的話,追蹤粉絲專頁吧!

我們每天至少分享 1 篇文章/新聞或者實用的軟體/工具,讓你輕鬆增廣見聞提升專業能力!如果你喜歡我們的文章,或是想了解更多特定主題的教學,歡迎到我們的粉絲專頁按讚、留言讓我們知道。你的鼓勵,是我們的原力!

贊助我們的創作

看完這篇文章了嗎? 休息一下,喝杯咖啡吧!

如果你覺得 MyApollo 有讓你獲得實用的資訊,希望能看到更多的技術分享,邀請你贊助我們一杯咖啡,讓我們有更多的動力與精力繼續提供高品質的文章,感謝你的支持!