學習 Git - 不小心刪掉的檔案救的回來嗎?


Posted by Calon on 2022-05-14

首先我們先來看一下工作目錄裡面有哪些檔案:

$ ls
configs  helloWorld.txt  new.txt

接下來使用 rm 來刪除所有 txt 檔:

$ rm *.txt
$ ls
configs

可以看到 txt 檔都背山除了,再來使用 git status 檢查狀態:

$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
    delete:   helloWorld.txt
    delete:   new.txt

no changes added to commit (use "git add" and/or "git commit -a")

2 個 txt 檔案都是被刪除的狀態,接下來我想要把 helloWorld.txt 救回來,可以使用 git checkout

$ git checkout helloWorld.txt
從索引區更新了 1 個路徑

再使用 git statusls 來看一下:

$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
    delete:   new.txt

no changes added to commit (use "git add" and/or "git commit -a")
$ ls
configs  helloWorld.txt

helloWorld.txt 有回來了,這次我們先把 configs 這個目錄刪除後,再把它和 new.txt 一起救回來:

$ rm -rf configs
$ ls
helloWorld.txt
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
    delete:   configs/password.txt
    delete:   new.txt

no changes added to commit (use "git add" and/or "git commit -a")

如果要一次把剛刪除的檔案和目錄救回來的話:

$ git checkout .
從索引區更新了 2 個路徑

再用 lsgit status 來檢查一下:

$ ls
configs  helloWorld.txt  new.txt
$ git status
On branch master
nothing to commit, working tree clean

configs 和 new.txt 都有成功救回來了。

Git 是怎麼救回檔案的?

git checkout 除了在後面會介紹到分支時會用來切換分支之外,在這裡當我們使用 git checkout 並且後面加上檔名或是路徑的時候,Git 會將檔案從 .git 拉一份到工作目錄。

準確來講是將暫存區的檔案覆蓋到當前工作目錄,這也是為什麼使用 git checkout 後會出現「從索引區更新了 x 個路徑」,因為暫存區是一個簡單的索引文件,指的是 .git/index。
所以如果在編輯檔案後不小心刪掉並用 git checkout 救回來,剛剛編輯過的檔案沒有加入暫存區或是提交 commit,雖然檔案救回來了但是剛編輯的內容是就不回來的。


參考資料

#Git







Related Posts

原始型別(傳值By Value ) v.s 物件型別(傳參考By Reference)

原始型別(傳值By Value ) v.s 物件型別(傳參考By Reference)

936. Stamping The Sequence

936. Stamping The Sequence

一個? 兩個??黑人問號

一個? 兩個??黑人問號


Comments