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

  1. Steps to stashing only one file
    1. Viewing history
    2. Staging files
    3. Unstaging the file
    4. Staging the file
  2. Stashing
  3. Adding Changes

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

Steps to stashing only one file

Assume you have six files and all of them have been changed. Now let’s we what steps should be taken to stash only one of them.

  1. Viewing history

    Firstly, run the git status command and all the files will be shown as unstaged:

    git status
  2. Staging files

    Execute the git add command to stage all the six files. For example, if that one file is the file3 that you want to revert then it will be like this:

    git add
  3. Unstaging the file

    Next step is unstaging the file3 with the help of git reset:

    git reset file3
  4. Staging the file

    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. 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