--- title: Git description: 整理常用 Git用法或指令。 img: alt: author: name: Jack.hu bio: img: tags: - git --- # Git ## 基本用法及指令 ### 用法 1. use first ```bash= # 建立.git檔 $ git init # 建立遠端連線 $ git remote add origin <https://...> # 添加全部 新/異動 檔案 $ git add . # commit $ git commit -m <'message'> # 設置預設路徑並push至github/gitlab/... # 下次直接 git push即可。 $ git push -u origin main ``` 2. after use first Do 1. row 6 - row 10 again 3. back to other commit history ```bash= # check 目前版號資訊 $ git log # --hard 表示當前的檔案,如不加只會改變版號而不會改變內容物。 $ git reset --hard <log version> # 查看版號並確認是否真的還原成功 $ git log ``` 4. forward to origin version ```bash= # check 目前版號及歷史版號 $ git reflog $ git reset --hard <log version> $ git log ``` \* 如果下`git reset`發現沒有變回來,就表示忘了加`--hard`,直接在下一次重新輸入指令時記得加上`--hard`就可以了!!! ### 指令 ```bash= # download repo $ git clone # check current status $ git status # check log $ git log # check branch [create new branch] $ git branch [branch name] # check commit history $ git blame # 前往分支 $ git checkout <branch name> # 刪除分支 # 注意,無法刪除目前所在的分支,需要切換到別的分支才能刪除本來所在位置的分支!!! $ git branch -D <branch name> ``` ## 進階用法 ### 複雜情境 1. > 現在有兩個RD,RD1異動test1.txt中func1並新增test2.txt,RD2修改test1.txt中func2並新增test3.txt > > 此時RD1先做完並commit and push並告知RD2他做完了,RD2想說先pull下來他的檔案再繼續修改, > > 但他遇到無法先pull下來,他該怎麼做才能把RD1檔案pull下來並不會覆蓋自己已經寫好的func2? > > 此時有兩種做法 > 方法一、commit(鎖定住檔案被追蹤的狀態) > 方法二、stash(***建議使用**,這樣之後維護比較好追蹤!!!) > > 以下僅呈現方法二 ```bash= $ git add . $ git stash save <封存名稱> # check 目前有哪些stash $ git stash list # 把RD1檔案download and merge $ git pull # 把剛剛第二步驟封存的資料加回來到目前分支並刪除此stash $ git stash pop stash@{0} ``` \* 如果stash裡面有多餘的不想用,可用`git stash drop stash@{1}` 就可以直接從stash裡面刪除!!! --- ## 其他 ### 一、如何讓每個repository擁有不同git user? ```bash= $ cd <your repository dir> $ vim .git/config ``` + 添加以下項目至文檔。 ```vim ...以上內容省略 [user] name = <你的名稱,可隨意輸入> email = <你的git帳號,通常是註冊的電子郵件信箱> ``` + 儲存並離開vim,即可針對此repository進行相關命令操作。 ### 二、遇到自建立的git並且無SSL憑證的錯誤訊息,如何處理? + 此問題主要是因為git有限制使用http時,需要使用SSL憑證才能執行相關下載或操作。 ```bash= $ cd <your repository dir> # 添加 -c http.sslVerify=false,可讓git單次忽略SSL憑證並執行該命令。 $ git -c http.sslVerify=false <cmd> ``` ### 三、git stash 新檔案(untracked) + 此問題主要是因為git stash原則上只會stash已被tracked或之前的舊檔案(如有異動到),但有時候開發新功能會新增新檔案。 ```bash= $ cd <your repository dir> $ git stash -u # 即可連同新舊檔案都stash. ``` ### 教學資源 1. 線上沙盒教學 https://learngitbranching.js.org/?fbclid=IwAR2OB-Lu-2blPXJVOsiqdCpzMZJ1TCFJEkB1KYFBrw0qsa1i5b0SkVy8B8g&locale=zh_TW ###### tags: `git`