How to git stash one file and add a message

🌸️ 2 mins read

Git stash might be one of the most useful git commands in my opinion. We can understand git stash as a drawer where we want to keep temporarily some work done in a file (or multiple files) to keep on working on it afterwards.

The common use is:

> git stash

To store everything in the working directory (meaning "everything tracked", which is everything that is not committed but new files not tracked yet).

And then, to recover it:

> git stash pop

You have also git stash apply, which will safely recover the stashed files but leaving the copy in the stash. I'd rather use pop, that deletes the copy from the stash, to keep it as tidy as possible.

To see what is in the stash, you can list its content with:

> git stash list

It gives you a zero-based indexed list. Something like:


stash@{0}: On branch-blah-blah 8675765 something
stash@{1}: On branch-blah-blah 8675123 something

With pop and apply (the command we've just seen: "git stash pop or git stash apply") you can also get an specific "stash" from the list with stash@{n}, being n the item index in the list.

But let's take a look at that "something" I added (as an example, of course). That would be normally a commit message corresponding to the last commit message you have in you commit history. But I'd prefer to put something more meaningful, like a "custom commit message", but for the stash. Is like labelling the box (imaginary πŸ“¦) I'm putting things inside.

For that end, you'd do:

> git stash save 'These files are an improvement over...'

(Something that makes sense to you.)

But, as I said, that will add everything in the "working directory" (BTW, "working directory" means an specify thing in Git, I invite you to look that up if you don't know it πŸ˜‰).

And, here we come: what if I only want to add 1 file to the stash?

Git push, it is

From the docs, git push has several options; for adding one file could be something like:

> git stash push -- nuxt.config.js

Being `nuxt.config.js` the file I want to save, preceded with `--`.

And for adding a message, the full command would be: πŸ₯πŸ₯πŸ₯

> git stash push -m 'some message' -- nuxt.config.js

That's the command to stash one file with a message. πŸ˜‰

Thanks for reading! Have a nice day!