How to remove a file from the index in git?

后端 未结 6 724
[愿得一人]
[愿得一人] 2020-12-07 07:34

How to remove a file from the index ( = staging area = cache) without removing it from the file system?

6条回答
  •  粉色の甜心
    2020-12-07 08:02

    Only use git rm --cached [file] to remove a file from the index.

    git reset can be used to remove added files from the index given the files are never committed.

    % git add First.txt
    % git ls-files
    First.txt
    % git commit -m "First"   
    % git ls-files            
    First.txt
    % git reset First.txt
    % git ls-files              
    First.txt
    

    NOTE: git reset First.txt has no effect on index after the commit.

    Which brings me to the topic of git restore --staged . It can be used to (presumably after the first commit) remove added files from the index given the files are never committed.

    % git add Second.txt              
    % git status        
    On branch master
    Changes to be committed:
      (use "git restore --staged ..." to unstage)
        new file:   Second.txt
    % git ls-files       
    First.txt
    Second.txt
    % git restore --staged Second.txt
    % git ls-files 
    First.txt
    % git add Second.txt 
    % git commit -m "Second"
    % git status            
    On branch master
    nothing to commit, working tree clean
    % git ls-files 
    First.txt         
    Second.txt
    Desktop/Test% git restore --staged .
    Desktop/Test% git ls-files
    First.txt                   
    Second.txt
    Desktop/Test% git reset .                    
    Desktop/Test% git ls-files
    First.txt
    Second.txt
    % git rm --cached -r .
    rm 'First.txt'
    rm 'Second.txt'
    % git ls-files  
    

    tl;dr Look at last 15 lines. If you don't want to be confused with first commit, second commit, before commit, after commit.... always use git rm --cached [file]

提交回复
热议问题