Search code examples
gitstage

Git: ability to stage a certain file content without touching the working tree


I want to modify the index of one (text) file without having to change the working tree file state. Is this possible?


Solution

  • Another take on "changing file in index without altering working dir" is to apply a patch to index only. This is often the way GUI git clients stage only selected lines from a given file.

    You start out by (if you want) clearing out the changes from index for that file:

    git reset path/to/file
    

    Then extracting the full patch for it

    git diff path/to/file > /path/to/tmpfile
    

    Edit the patch file to include only the changes you want to apply, and apply just the edited patch:

    git apply --cached /path/to/tmpfile
    

    See:

    git help apply