寫在前面
如果只解釋命令的用法的話,我想,是非常枯燥,而且沒人願意去看,看了也學不會,學不會就用不了,用不了就.....就沒有然後了,所以,我準備模擬一個專案的建立和完整的流程,來介紹一些 git 的一些常用命令。
準備工作
還記得,上篇文章說的 GitHub 嗎?就是那個全球最大的同性交友社群,不說錯了,是最大的程式碼開源社群。因為Github 是一個用git做版本控制的專案託管平臺,所以沒有遠端伺服器的情況下,我們學習Git的話,可以藉助 GitHub 一下。
1.首先,你要有一個 GitHub 的賬號~,註冊地址GitHub
2.New repository,建立一個新專案倉庫,選擇 public型別,其他預設。

3.新增SSH keys,給你的 Github賬號新增SSH祕鑰對,免密碼登入,這步可以省略,但是建議不要。
建立倉庫後,會得到兩個倉庫地址,兩個地址的區別是一個使用 https,另一個使用 ssh 協議。


兩個地址都可以,但是使用 https 地址上上傳和下載程式碼的時候,都會讓輸入 GitHub 的程式碼,太繁瑣了。這裡推薦使用 ssh 協議地址,使用 ssh ,需要在你的電腦裝置和 GitHub之間配置SSH祕鑰對,公鑰放在 Github 上,私鑰放在你的電腦本地上,這樣使用有私鑰的這臺電腦,操作 GitHub 就不用輸入密碼了。
第一步輸入 ssh 命令,看電腦是否安裝 ssh 協議,如果沒有,去網上搜尋下載安裝,如果已經安裝,會得到下面的結果

然後使用 ssh-keygen -t rsa -b 4096
命令,生成私鑰對

命令執行完畢,會看到本地生成了兩個檔案,私鑰id_rsa
和公鑰id_rsa.pub
。
將 id_rsa.pub
的內容複製貼上到 GitHub 中(Setting-SSH and GPG keys-New SSH key)

Git 命令一日遊出發
接下來,我們會在本地電腦上建立一個空資料夾,在其中一個文字檔案,並推送到 GitHub 上面新建的 GitStudyDemo 中,一起看看,途中會遇到哪些命令吧。
git init
本地建立一個空資料夾,名字什麼都可以,我的叫 GitDemo,然後命令列進入到這個資料夾內,執行 git init 命令:

執行完畢,GitDemo 中會生成一個 .git 的隱藏檔案,生成這個檔案,就說明 GitDemo 已經是個 Git 倉庫了。(Mac系統快捷鍵 command+option+. ,Windows 勾選顯示隱藏檔案可以顯示隱藏檔案)
git 對專案版本控制的所有資訊,都儲存在這個 .git檔案中,現在這部分略過,以後運用熟了會逐漸意識到。
###git remote
在 GitHub 上面建立了遠端倉庫 GitStudyDemo ,在本地建立了 GitDemo 本地倉庫,現在我要把它們兩者連線起來,需要 git remote add 命令,將 GitStudyDemo 倉庫的遠端地址 新增到本地倉庫中。

新增成功後,使用 git remote -v 命令可以驗證一下。同時如果你有興趣對比下命令執行前後的話,會發現在 .git/config 中已經新增了遠端倉庫地址。
###git status
接下來,在 GitDemo 中新建一個檔案 test.txt,執行一下 git status ,看一下會發生些什麼。

提示資訊說 test.txt 是Untracked file(未跟蹤檔案),很清晰的建議我們執行 git add <file>
git status 這個命令顧名思義就是檢視狀態,這個命令可以算是使用最頻繁的一個命令了,建議大家操作關鍵命令之前,都先檢視一次,降低誤操作概率。
###git add git add 這個命令的意思是將修改的內容新增都暫存區,等待被提交。 執行 git add 後 再次執行了 git status 來檢視倉庫的狀態,以便和執行前做對比。

提示資訊發生了變化,提示Changes to be committed,也可以使用 git rm --cached 退出暫存區。這裡我選擇去提交
###git commit
git commmit -m <your commit message>, 這個命令的意思是,將暫存區的內容,設定一個提交的資訊,然後新增到提交歷史內容區中,等待被推送到遠端倉庫。
提交完執行 git status ,顯示工作區沒有檔案需要提交。

###git push & git pull
現在我們要開始把本地的倉庫 GitDemo 推送到遠端倉庫 GitStudyDemo了,使用的命令是 git push 。

這裡注意,因為我們是第一次建立,遠端倉庫中什麼都沒有,所以直接 push 就可以了,但是真實的專案開發中,push 之前都要先操作一下 git pull 動作,把遠端倉庫中的內容拉取下來,再操作 git push。
###git branch
分支,是 Git 的核心特色,在團隊合作的時候,發揮的尤其出色。一個開發者一個分支,然後在留一個主分支做樹幹,每個開發者完成之後,將自己分支的內容匯聚到主分支上。關於分支有很多種玩法,接下來開始稍微體驗一下。
首先檢視一下當前專案有多少個分支:

git branch 檢視本地分支,加上 -a 引數可以檢視專案所有分支,包括遠端分支。 分支名稱前 *
表示是當前分支。
然後建立一個分支:

###git checkout
建立完分支後,切換分支,使用的命令是 git checkout ,注意執行後 *
號 跑到 test 分支前面了。

###git merge
然後我們在當前分支中在 test.txt 中新增一句話 'Hello Git !' ,然後執行 git add &git commit .
再使用 git checkout 切換回 master 分支。檢視test.txt,發現沒有'Hello Git !' 中的內容。再切換回 test 分支中,檢視test.txt,發現有'Hello Git !',是不是很神奇?
分支用起來就是這麼好玩,如果想讓 master 中的test.txt 中也有這句話的話,可以選擇合併 test 分支。

一日遊結束,今天解散,明天見
上面基本是日常的工作中,出現頻率非常高的 git 命令,但這不是全部,因為還有很多很多好用好玩的,在下面幾篇文章中,等待著我們,下篇文章見~
