How to ignore any changes on already committed file to Git

This question already has an answer here:

  • Ignore files that have already been committed to a Git repository [duplicate] 21 answers

  • Only untracked files (not added to Git) can be ignored. Or in other words ignoring is about files which are not known to Git, ie are not in the index (have no entry in the staging area).

    To make a file untracked (removing it from the index, and thus staging it from deletion in the next commit), but keep it in the working area ie in the filesystem, you can use

    $ git rm --cached <file>
    

    The file will be removed from remote repository (from the tree of top commit - it will be still present in history) after local commit, and after push to remote.


    If you want for Git to ignore changes so that git diff and git status would not report them, and git commit -a would not commit them (but git add <file> + git commit and git commit <file> would still add them), you can lie to Git with this trick (see git ready » temporarily ignoring files article):

    $ git update-index --assume-unchanged <file>
    

    The git update-index command is low-level (plumbing) command. You can find which files are " assumed unchanged " with:

    $ git ls-files -v
    h <file>
    

    git ls-files -v uses lowercase letters for denoting status files that are marked as assume unchanged.

    You can turn it off with

    $ git update-index --no-assume-unchanged <file>
    

    Note that this option original purpose is speeding up status on platforms where stat is slow.


    Following @Dave comment, and referenced Git - Difference Between 'assume-unchanged' and 'skip-worktree' question, another option in modern enough Git is making Git do not use working area version with skip-worktree bit.

    You can turn it on for a tracked file with

    $ git update-index --skip-worktree <file>
    

    This makes Git use the index version (the last committed version) in place of the version from the filesystem. You can check which files have this bit set with

    $ git ls-files -v
    S <file>
    

    The git ls-files -v command will use S to denote files with "skip-worktree" set.

    Note that this option original purpose is support for sparse checkout.


    The .gitignore just tells git which untracked files to ignore, so it won't do anything if your file is already tracked by git. Instead you can tell git to temporarily ignore any changes to a tracked file using this command:

    git update-index --assume-unchanged <file>
    

    And if you ever want to undo this, just run:

    git update-index --no-assume-unchanged <file>
    

    See here for more details.


    Untrack the files that you want to ignore:

    git rm --cached <file>
    

    Then you can add files and .gitignore will not track ignored files.

    链接地址: http://www.djcxy.com/p/23414.html

    上一篇: 试图使用.gitignore文件忽略.log文件

    下一篇: 如何忽略已提交的文件到Git的任何更改