首先需要注冊 github 賬號及在本地安裝配置 git,使其本地可用。
1. 創建公鑰 (ssh-key)
ssh-keygen -t rsa -C “your email address”
一路回車選擇默認值后生成文件夾 ~/.ssh。
cd ~/.ssh
可以看到該文件夾下生成了 id_rsa.pub 文件。
2.添加公鑰到 Github 中
登錄 github 賬號,選中並打開 setting,選擇 SSH and GPG keys,選擇 New SSH key,在 Title 中填入題目,在 Key 中填入id_rsa.pub 文件中的公鑰。
注意不能在 vim 中復制 id_rsa.pub 文件中的內容,否則會報錯:
Key is invalid. You must supply a key in OpenSSH public key format.
可用如下命令驗證上述配置是否成功:
ssh -T git@github.com
若出現 Are you sure you want to continue connecting (yes/no)? 選擇 yes。
出現 You've successfully authenticated, but GitHub does not provide shell access. 說明配置成功。
3.在本地建立新倉庫並將其關聯到遠程倉庫
(1)建立本地新倉庫
建立新的文件夾當本地倉庫。
mkdir repository_name #建立新的本地倉庫
cd repository_name
git init
git add filename # (or git add *.*)
git commit -m "first commit"
在 Github 上相應的創建新遠程倉庫。
點擊 New 進入創建新倉庫界面,在創建倉庫界面填入相應的信息。
將本地倉庫與遠程倉庫關聯起來。
git remote add origin https://github.com/username/repository_name.git
git push -u origin master
若出現錯誤:error: The requested URL returned error: 403 Forbidden while accessing ...
修改 .git/config 文件中的 url
url = https://github.com/username/repository_name.git #修改前 url = https://username:password@github.com/username/repository_name.git #修改后
4. 加入團隊遠程倉庫
首先團隊倉庫是存在的,並且已經收到團隊倉庫的加入邀請或許可。
團隊倉庫一般是 private,先把團隊倉庫的代碼拷貝到本地
git clone htttps://username:password@github.com/team_name/team_repository_name
抓取所需分支
git fetch origin remote_branch_name:local_branch_name
轉到所需分支
git checkout local_branch_name
5.git其他常用操作
(1) 建立新的分支
git checkout -b new_branch
(2) 添加文件並備注信息
git commit -a -m "commit information"// 添加所有文件
git commit filename -m "commit information"// 添加某個文件
(3) 向遠程添加分支
git push origin local_branch_name:remote_branch_name
(4) 刪除本地分支
git branch -D branch_name
(5) 修改本地分支名稱
git branch -m old_branch_name new_branch_name
(6) 本地回退到之前的分支
git log
記錄 commit 后面的分支內容
git reset --hard commit后面的內容