How to Stash Only One File out of Multiple Files that Have Changed in Git
During the work on a project you can change a range of files, and there can be cases when all the changes except one should be added to the commit. One of the solutions is adding only the files that you want to add to the commit. But, when the changed files are too many, and you don’t want to commit the changes of only one of them, you can stash that file and commit all the changed files. Here, you will figure out how to stash a single file.
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.
Viewing the changed files
Firstly, run git status to see the list of the changed files:
Execute the git add command to stage all the six files:
git add .
Unstaging the file
Next step is unstaging the file3 with the help of git reset:
git reset file3
Stashing the file
Stash 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.
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.
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.