[Git] 使用 mv 和 git add 將一個目錄下所有檔案搬移至另一個目錄下

[Git] 使用 mv 和 git add 將一個目錄下所有檔案搬移至另一個目錄下

最近想把 Git 管理下的其中一個子目錄搬移到另一個子目錄下面,

原本以為得用 git mv 來做,但後來查了一下,

原來有更方便的方式,直接 mv 後再用 git add 就能搞定了,來看看吧~

 

舉例來說,~/GitTest 下有 a, b, c, d 四個檔案:

testuser@localhost ~/GitTest $ ll
total 32
-rw-r--r--  1 testuser  staff  2 May 24 00:06 a
-rw-r--r--  1 testuser  staff  2 May 24 00:06 b
-rw-r--r--  1 testuser  staff  2 May 24 00:06 c
-rw-r--r--  1 testuser  staff  2 May 24 00:06 d

 

我想做的事是把這幾個檔案都搬移至新建立的 new 目錄下:

testuser@localhost ~/GitTest $ mkdir new
testuser@localhost ~/GitTest $ mv a b c d new/

 

這時候 git status 會說 a, b, c, d 四個檔案要被刪除了,多了一個沒看過的 new 目錄:

testuser@localhost ~/GitTest $ git status
On branch master
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
deleted:    a
deleted:    b
deleted:    c
deleted:    d
Untracked files:
(use "git add <file>..." to include in what will be committed)
new/
no changes added to commit (use "git add" and/or "git commit -a")

 

這時只要下 git add -A,-A 這個選項就會將所有新增/修改/刪除的檔案都加到索引去,

也就是說會將 a, b, c, d 從索引中移除,但將 new 目錄加到索引~

而 git 很聰明,它知道 new 目錄下的檔案內容和 a, b, c, d 都一樣,

因此判斷是一個搬移檔案的動作:

testuser@localhost ~/GitTest $ git add -A
testuser@localhost ~/GitTest $ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed:    a -> new/a
renamed:    b -> new/b
renamed:    c -> new/c
renamed:    d -> new/d

 

這時候下 git commit 就能讓檔案搬移的動作也記錄在 git 中囉~

比起對每一個檔案都下 git mv 比起來,真的是方便許多的做法喔~

 

參考資料:stackoverflow: git command to move a folder inside another

 

(本頁面已被瀏覽過 1,100 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料