# git ## 甚麼是git git 是程式碼控制軟體 在甚麼時間寫了甚麼程式,誰寫的都可以記錄 程式碼上傳到遠端資料庫也可以利用git,而且更方便 ## Local Repository #### git設定個人資訊 ```bash! git config --global user.name "姓名" git config --global user.email "Email" ``` #### 查詢設定 ```bash! git config --list ``` config位置 `.\.git\config` #### 初始化資料庫 ```bash! git init 資料夾 ``` #### 加入索引 ```bash! git add . ``` #### 提交版本 ```bash! git commit -m "版本資訊" ``` #### 查看資料夾狀態 ```bash! git status ``` #### 查看版本紀錄 ```bash! git log ``` ## Remote Repository #### 增加遠端數據庫 ```bash! git remote add 數據庫名稱 數據庫網址 ``` 數據庫名稱可以自己命名 #### 更新資料到遠端 ```bash! git push 數據庫名稱 分支名稱 ``` #### 下載數據庫 ```bash! git clone 數據庫網址 ``` 如果只想 clone 最新 commit 節省空間,在後面加`--depth=1` #### 更換遠端網址 ```bash! git remote set-url 數據庫名稱 新網址 ``` ## 分支 #### 新增分支 ```bash! git branch branchName ``` #### 切換分支 ```bash! git checkout branchName ``` #### 刪除本地分支 ```bash! git branch -d branchName ``` #### 刪除遠端分支 ```bash! git push :branchName ``` #### 分支合併 - 快轉 (fast forward) ```bash! git merge 分支名稱 ``` #### 分支合併 - 非快轉 ```bash! git merge branchName --no-ff ``` ## 恢復版本 原: ![](https://i.imgur.com/JpF53f8.png) ```bash! git checkout c2174d ``` ![](https://i.imgur.com/CxCXHSr.png) 後: ![](https://i.imgur.com/OTG18cI.png) 回到最新 ```bash! git checkout main ``` ## ssh key :::success 強烈建議使用 push 到 github 使用 ssh 較安全也方便 ::: [參考來源](https://www.maxlist.xyz/2022/12/22/github-ssh-setting/) 1. 使用 ssh-keygen 產生 publich key ```bash! ssh-keygen ``` 2. 複製id_rsa.pub ```bash! cat ~/.ssh/id_rsa.pub ``` 3. 將 publish key 貼到 Github 上 到 [Github 設定頁面](https://github.com/settings/keys),點擊新增 New SSH key,再把剛剛複製的公鑰貼上 ![github](https://hackmd.io/_uploads/SJlmlAolJe.png) 4. 測試 ```bash! ssh -T git@github.com ``` ![image](https://hackmd.io/_uploads/ryUxP7ZWyl.png) 之後新增或 clone 儲存庫就用 ssh 的連結 ![image](https://hackmd.io/_uploads/SkNWikwp1x.png) :::warning #### 將儲存庫改為ssh方式連線 如果之前已經用https新增遠端儲存庫的,先刪除 ```bash! git remote remove 儲存庫名稱 ``` 再新增ssh的 ```bash! git remote add 儲存庫名稱 git@github...... ``` ::: ## pull衝突 ```bash! git pull - rebase ``` ## gitignore 中途才寫 `.gitignore`,已經加入追蹤的檔案還是會被追蹤 解法: ```bash! git rm -rf --cached . git add . ``` ## 在電腦中建立類似 remote repository 的儲存庫 ```bash git init --bare ``` 這種方式,git 不會建立 .git 存放內容,而是直接建立在資料夾中 ``` ls . branches config description HEAD hooks info objects refs ``` 之後就可以把這個資料夾當作 remote repository 來使用 ```bash git remote add local path/to/dir git push local main git pull local main ```