情境1: 建立新的repo
- 想要將local的檔案資料建立Git控管,將資料都歸檔到一個目錄,或是從空的目錄開始,先
cd
進到該目錄透過git init
就會建立git repo git status
檢查狀態git add
將要控管的檔案加入stagegit commit
將stage的檔案提交,並且要寫入這版本修改了什麼git log
查看commit紀錄
情境2:找到可參考的Git Repo, fork到自己的Repo, Clone到local Repo
- 直接到要fork的Git page上點下fork按鈕,就會將該專案fork到你的Git帳號
fork之後如果是要另做其他用途,可以先改名
- 點選Clone or download,點選後會顯示URL,也就是git clone要填入的URL
git clone URL
,其實也可以直接點選Open in Desktop,用Git Desktop幫你完成
- 完成
情境3:在local端commit了準備要push到remote,發現有些有關隱私的資訊也在裡面沒有移除,或是已經commit的revision要移除
透過git reset --soft HEAD^
可以將前一版commit取消,當然多做幾次就可以把之前做的消光光,–soft可以自動將working tree放到stage,也就是目前檔案已修改過的保留,這樣可以重新整理要commit的內容,如果是用–hard就會將修改內容回復,要謹慎使用,或是先將local repo先備份到另一個資料夾,先試看看比較保險
情境4: 將資料上傳
git fetch origin
來同步遠端伺服器上的資料到本地 git push origin
來上傳本地資料
情境5: 本地端已經準備好git repo,準備新增github repo,並且上傳
git init
init本地端repogit add *
加入所有檔案 git commit
commit檔案 到GitHub先create project git remote add master https://github.com/maycehsu/xxx-name.git
新增github git push -u origin master
將本地repo上傳
情境6: ignore changes
git checkout -f master
情境7: sync遠端repo
上傳 git push origin master
下載 git pull origin masster
情境8: 當remote repo是在遠端ssh server上,需要用private key登入
當設定完remote repo
git remote add origin ssh://user@xxx.xxx.idv.tw:/opt/repo.git
git push origin master
卻出現error
Permission denied (publickey).
fatal: Could not read from remote repository.
如果remote ssh server是使用private key登入, 使用-i指定private key (例如當你使用Amazon EC2 server, 就是用指定private key登入)
ssh -i key.pem user@xxx.xxx.idv.tw
此時我們要讓git知道當連線到這台server要用哪個private key就要設定~/.ssh/config檔案,內容如下
host xxx.xxx.idv.tw
HostName xxx.xxx.idv.tw
IdentityFile ~/.ssh/key.pem
User user
情境9: 建立branch
建立分支
git checkout -b new_branch
等同於
git branch new_branch
git checkout new_branch
列出現有branch
git branch -v
rename branch
git branch -m <old> <new>
or change current branch git branch -m <new-name>
情境10: 將已存在local git repository上傳到EC2 server
建立/opt/git目錄給git server用
cd /opt
sudo mkdir git
sudo chown ubuntu:ubuntu git
將local repository匯出bare repository並且上傳到EC2 server上/opt/git下
git clone myproject myproject.git
scp -i EC2key.pem -r myproject.git ubuntu@<ec2-ip>:/opt/git/
將local repository push到remote,因為我已經有用github了,所以在local端的.ssh內有github_rsa.pub,所以先透過scp將github的public key也加到EC2 server上的authorized_keys
scp -i EC2key.pem ~/.ssh/github_rsa.pub ubuntu@<ec2-ip>:/home/ubuntu
cat github_rsa.pub >> ~/.ssh/authorized_keys
將local repository加到remote repository,因為git已經預設用github的public key了,而我們也已經將這把key放到EC2 server的autorized_key上了,所以push到EC2 server時就能認證完成
git remote add origin ssh://ubuntu@<ec2-ip>:/opt/git/myproject.git
git push origin master
情境11: EC2 server下載repo
建立目錄new_project, 並設定remote repo
mkdir new_project
cd new_project
git init
git remote add origin ssh://localhost/opt/git/new_project.git
git pull origin master