Git

How Can I Stash Only Staged Changes in Git?

While tracking multiple newly created project files from the working area to the staging index, developers encounter errors. They want to resolve these errors without removing/deleting all added modifications from the staging index. In such cases, they are required to stash the changes by executing the “git stash” command with the “–keep-index” option to hold the existing staging index changes.

This blog demonstrated the process of stashing only stage changes in Git.

How Can I Stash Only Tracked Changes in Git?

In order to stash the stage changes in Git, perform the provided steps:

  • Navigate to the Git repository.
  • Check the list of repository content.
  • View the current working repository log history.
  • Use the “git stash –keep-index” command.
  • To push the new stash message to the index, execute the “git stash push -m “<stash-message>” command.

Step 1: Move to Git Repository

First, switch to the Git desired directory with the help of the provided command:

$ cd "C:\Users\nazma\Git\perk2"

Step 2: Display Repository Content

Then, execute the “ls” command to view the existing content of the current working repository:

$ ls

According to the below-given output, the local repository contains multiple files having different extensions:

Step 3: View the Reference Log History

Next, execute the following command to show the commit log history:

$ git log .

Step 4: Stash Staged Changes

Finally, stash the tracked changes of the current working repository by running the “git stash” command:

$ git stash --keep-index

Here, the “–keep-index” used for temporary holding the staging index changes:

Step 5: Show Stashed Data With Index

After that, execute the “git show” command along with the most recent stash index to view its content in detail:

$ git show stash@{0}

Step 6: Push Stash

Now, to push the stashed changes with a new stash message, utilize the “git stash push” command:

$ git stash push -m "stash changes"

Here, the “-m” option indicates the message, and “stash changes” is the new stash message:

Step 7: Verify New Stash Message

Lastly, display the list of all existing stashes and ensure whether the new stash message is pushed successfully or not:

$ git stash list

That’s it! We have compiled the easiest way to stash the stage changes in Git.

Conclusion

To stash the stage changes in Git, first, move to the desired Git repository and check its list of content. Then, view the current working repository logs history and use the “git stash –keep-index” command. After that, push the new stash message to the index by running the “git stash push -m <stash-message>” command. This blog demonstrated the process of stashing only stage changes in Git.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.