如何將檔案從stage移除

2021-07-27 08:29:20 字數 2377 閱讀 9173

git將檔案分成三個階段

- working directory

- stage

- repository

要進入repository之前,必須先進入stage,但實際上可能用了git add之後,才後悔發現這個檔案不應該進stage,必須從stage中移除,由於必須考慮該檔案是否已經存在於repository,所以必須用不同的git指令才能達成該效果。

git 2.6.4

我們知道在git裡,要講檔案commit進repository,需要進過兩個步驟:

1. 用git add將檔案寫進stage

2. 用git commit將檔案寫進repository

實際應用中經常遇到一種狀況:當用了git add後,才發現新增錯檔案了,必須將檔案從stage中移除。

乙個看似很單純的需求,在git下卻要分兩個不同的狀況去思考:

1.若該檔案不再repository內:git rm --cached filename

2.若該檔案已經在repository內:git reset head filename

先了解git rm --cached背後的原理:

1.若檔案存在與stage和repository中時,會將檔案從repository中刪除,並且從stage中刪除,但不會刪除本地的實際檔案,不過由於檔案已經從repository中刪除,檔案會從tracked變成untracked

2.若檔案存在與stage,卻不存在與repository中,會將檔案從stage中刪除,但不會刪除本地的實際檔案。由於repository中本來就沒有這個檔案,所以該檔案一樣會是untracked狀態。

回想我們的狀況:

1.若該文件不存在repository中:git rm --cached會幫我們從stage刪除,且檔案本來就是untracked,執行完還是untracked,符合預期。

2.若檔案已存在repository中:git rm --cached會幫我們從repository中刪除,並且從stage中刪除,因為已經從repository中刪除了檔案,檔案會從tracked變成untracked,這並不符合我們的預期。

這說明了為什麼檔案在repository時,我們一定不能用git rm --cached

先了解git reset head背後的原理:

head為目前最新的commit節點,git reset head表示將檔案還原到目前最新的commit。以下為支援的引數,若沒有任何引數,預設為--mixed

1.--soft:repository的檔案會被還原到head,但stage與working directory檔案不變。

2.--mixed:repository與stage的檔案都會被還原到head,但working directory的檔案不變。

3.--hard:repository、stage和working directory的檔案都會被還原到head。

回想我們的狀況:

1.若檔案不在repository中:git reset head會出現以下錯誤:

fatal: ambiguous argument 'head': unknown revision or path not

inthe working tree.

use '--'

to separate paths from revisions, like this:

'git [...] -- [...]'

因為檔案根本還沒進repository,也就是還沒有commit過,哪來的head呢?git馬上給你錯誤資訊,這並不是我們預期的。

2.若檔案已經在repository中:git reset head會幫我們將repository與stage還原到目前最新commit節點檔案,但working directory的檔案不會被還原,因為stage的檔案已經不是目前的檔案,所以檔案的狀態由原本的stage變成modifed,符合我們的預期。

這解釋了為什麼檔案不存在於repository時,不能用git rm --cached而得用git reset head

Git如何將檔案重新命名

第一種方法 1.本地重新命名 root git git test git status on branch master changes not staged for commit use git add rm to update what will be committed use git che...

如何將csv檔案匯入MySQL

root debian mysqlimport uroot p123456 fields terminated by fields enclosed by fields escaped by database name var lib mysql files table name.csv引數說明 f...

如何將 hex檔案轉化為 c檔案

說明樓主太初級,迷戀於c。1 c與hex並不是一一對映的,有可能n個人寫的c,會出同乙個hex,你希望回成哪個人寫的呢?或許你可能說 任意乙個孝可以,只要能轉c就行。同乙個c程式,用不同的編譯器去編譯生成的hex也不一定相同。2 將hex轉c是很困難的事,只有c的超級高手才有可能還原,也只是 可能 ...