# Git 筆記 ## 基本常用 ```cmake= git config --global user.name "你的名字" git config --global user.emaiul "你的信箱" ``` - `git init` 在本地創建一個 .git 文件 - `git add .` 表示把工作區的全部文件提交到暫存區 - `git commit -m "xxx"` 把暫存區的文件提交到倉庫 - `git remote add origin https://github.com/name/project/git` 把本地倉庫跟遠端的倉庫連接起來 - `git push -u origin master` 把倉庫區的文件提交到遠端的倉庫 一旦提交後,如果沒有對工作區做任何改變的話,那麼這個工作區就是乾淨的,會有這樣的訊息:`nothing to commit, working tree clean` ## 還原相關 - `git log` 查看版本號 - `git reset --hard + 版本號` 即可回朔到指定的版本 - `git reset HEAD^` 如果 commit 後,想反悔本次的 commit 內容可以下達這個指令還原此次的 commit ## 分支 - `git branch` 查看所有分支 - `git branch xxx` 創建分支 - `git checkout xxx` 切換到該分支 - `git checkout -b xxx` 創建並且切換到該分支 - `git branch -d xxx` 刪除該分支,但是有可能會失敗,因為 git 會保護沒有被合併的分支 - `git branch -D xxx` 強制刪除,丟棄沒有被合併的分支 - `git branch -a` - `git branch -d test` 移除本地端的 branch `假想情境` 用一個新的分支做提交 (分支名:other) ```cmake= // 目前是在 other 分支位置 // 提交 other git add . git commit -m "first commit" // 切換回 master git checkout master // 此時,master 沒有 other 的文件,因為分支還沒有合併 git mergee other // 合併完成後,就可以在 master 分支上看到 other 的文件 ``` ## 工作到一半臨時需要切換分支 在 A 分支工作的時候,臨時要切換到 B 分支處理緊急事情時,可以先把當前的程式碼儲存起來,等 B 分支處理完在切換回 A 分支的時候再還原。 - `git stash` 把工作區的文件暫存起來 - `git stash apply` 恢復卻不刪除 stash 內容 - `git stash drop` 刪除 stash 內容 - `git stash pop` 恢復的同時也把內容刪除 - `git stash list` 查看 ## 多人協作 - `git remote` 查看遠程的庫 - `git remote -v` 顯示更詳細的資料 - `git push -u origin master` 推送 master 到遠程 origin - `git push -u origin other` 推送 other 到遠程 origin ## 其他 - `git status` 查看當前得狀態 - `git diff` 檢查差異 - `git clone xxxx.git` 下載 clone 文件 - `git relog` 顯示命令歷史 - `git rm` 刪除版本庫的文件 - `git log --graph` 查看分支的合併圖 ## 將 branch 整個覆蓋掉 master 情境:已經擁有 master + paytest 兩個 brach,想要把 paytest 整個覆蓋掉 master 的內容。 1. 先到當前的 master `git reset --hard origin/paytest` 2. 執行上方的代碼後,基本上 master 就已經被 paytest 取代,然後再將本地端分支強行推到遠程分支上面 `git push -f` ## 移除遠端分支 `git push origin :cat` https://backlog.com/git-tutorial/tw/reference/remote.html ## githubflow 從原始專案 fork 一份下來在自己的帳號底下 可以先檢查一下專案的地址 `git remote -v` ``` origin git@github.com:xxx/github-flow.git (fetch) origin git@github.com:xxx/github-flow.git (push) ``` ## 自定義指令 git alias ``` git config --global alias.st status git config --global alias.br branch git config --global alias.ck checkout ``` ## 編輯 commit 紀錄後, 同步遠端機器的 commit 紀錄 ``` git reset --hard origin/master ``` https://dotblogs.com.tw/michaelfang/2016/09/07/git-reset-log-reflog ### git 功能開發錯分支 ``` git stash git branch new_branch git checkout new_branch git stash pop ```