學習 Git (2) - 開始使用 Git 進行版本控制


Posted by Calon on 2022-04-25

檢查狀態

在一開始我們可以輸入 git status 來確認工作目錄的狀態,輸入之後會出現下面的資訊:

$ git status
On branch master

No commits yet

nothing to commit (create/copy files and use "git add" to track)

會看到最後一句無檔案要提交(nothing to commit),因為我們現在的目錄下還沒有任何資料,所以現在來新增一筆名為 HelloWorld.txt 的檔案,並再次使用 git status 來檢查狀態:

$ git status
On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
       helloWorld.txt

nothing added to commit but untracked files present (use "git add" to track)

會發現與剛才出現得訊息內容不一樣了,Untracked files 是「尚未被追蹤的檔案」,而下面出現的是我們剛剛所新增的 helloWorld.txt,也就是 helloWorld.txt 這個檔案尚未加到 Git 裡進行版本控制。

讓 Git 追蹤你的檔案

上面提到現在 helloWorld.txt 是「尚未被追蹤的檔案」,而要怎麼做才能讓 Git 對 helloWorld.txt 進行追蹤呢?
其實在 Untracked files 的下一行有寫到,"git add ..." 這句就是告訴你如何讓想要被版控的檔案加入到 Git 裡面做管理,現在我們就來在終端機裡面輸入:

$ git add helloWorld.txt

輸入完後再次使用 git status 來檢查現在的狀態:

$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
        new file: helloWorld.txt

可以發現狀態從 Untracked files 變成 new file 了,這表示我們已經將 helloWorld.txt 從工作目錄放到暫存區(Staging Area)了。
這時候有人會發現,這樣一個個把檔案慢慢打上去很麻煩,有沒有比較快的方法?
當然有,如果想要將所有 .html 檔都加入追蹤,可以使用萬用字元:

$ git add *.html

如果想要將目錄下的資料全部加到暫存區的話,可以使用 .

$ git add .

或是參數 --all

$ git add --all

. 和 --all 的差異

在比較舊的版本上(1.x)以及執行指令時的目錄位置而有所差異。

版本差異

在 1.x 版本中使用 --all 會將新增的檔案、修改的檔案、刪除檔案加入到暫存區,使用 . 則不會將刪除檔案加入到暫存區。不過在 2.x 版本之後兩者之間就沒有這種差異,但在使用時記得注意自己所使用的版本,避免與預期的結果不同。

執行時所在的目錄

假設今天我們新增了 sayHi.txt 之後,在工作目錄底下又新增了一個名為 dairy 的目錄,並且我們使用 cd 指令切換到 dairy 目錄底下去撰寫 2022-04-24.txt 檔案,並在 dairy 目錄底下執行 git add .,這時我們用 git status 來檢查:

$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
        new file: helloWorld.txt
        new file: 2022-04-24.txt

咦?為什麼新增的 sayHi.txt 沒有被加入暫存區?

這是因為 . 在相對路徑中指得是當前目錄,所以使用 git add . 只會將所在目錄的檔案以及子目錄、子子目錄……全部的變動加到暫存區裡,而在除此之外的變動都不會去理會。

可以將已加進暫存區再去做修改嗎?

假如今天我做了以下動作:

  1. 新增 test.txt
  2. 在裡面新增 'test, 1, 2, 3' 文字內容,並儲存關閉檔案
  3. 使用 'git add test.txt' 加入暫存區
  4. 修改 test.txt

執行到第 4 步後,使用 git status 來查看狀態:

$ git status
On branch master

No commits yet


Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
        new file: test.txt

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to update what will be committed)
   modified: test.txt

可以看到下面又多出了一個 modified(修改過)的狀態,這是因為我還沒有將變更過的 test.txt 加進暫存區,如果確定要這次變動的話可以使用 git add test.txt,如果想捨棄這次變動的話可以使用:

$ git checkout -- test.txt

執行完 git add 還不算完成一個完整的版控流程,最後我們還要使用 commit 將我們在暫存庫的資料放到儲存區才算是將一個版本儲存起來。
在下一篇就會來介紹 Git 的最後一步:Commit。


參考資料
  • 高見龍,《為你自己學 Git》

#Git







Related Posts

Day03 運籌帷幄

Day03 運籌帷幄

PM 工作流程解析與怎麼寫 PRD

PM 工作流程解析與怎麼寫 PRD

[筆記] Linux php模組、資料庫關聯、splunk串聯系統資訊

[筆記] Linux php模組、資料庫關聯、splunk串聯系統資訊


Comments