How to Stash Only One File out of Multiple Files that Have Changed

If you have a number of files that have been changed and want to revert only one of them to the last committed stage, then this snippet is for you. Assume you have six files and all of them have been changed.

Firstly, run the git status command and all the files will be shown as unstaged. For example, if that one file is the file3 that you want to revert then execute the git add command to stage all the six files:

git add

Next step is unstaging the file3:

git reset file3

Stage file3 with the git stash command to get it back to its original committed stage:

git stash --keep-index

Another way of stashing only one file is executing the following:

git stash save -p "commit message"

This method makes it possible to select which hunks should be added to the stash, whole files can also be selected. Read about the descriptions of each hunk here.

Stashing

The git stash command shelves changes made to the working copy so you can do another work, and then return and re-apply them. The command will stash the changes that have been added to your index (staged changes) and changes made to files currently tracked by Git (unstaged change. The --keep-index option left intact all the changes that are already added to the index.

Adding Changes

The git add command adds changes in the working directory to the index. It instructs Git to add updates to a certain file in the next commit. The primary role of this command is to promote changes in the working directory to the index. The index of Git gathers all the connected changes into highly focused snapshots. Then you can commit these changes to your project history.


Do you find this helpful?

Related articles