Book Your Free Call

How To Stash One File In Git?

Tim Mouskhelichvili
Tim Mouskhelichvili
2 minutes to read

Sometimes when working on a Git repository, a developer may want to stash single files instead of all the changes. Luckily, Git offers simple commands to manage the stash and to add a single file to the stash quickly.

To push one file to the stash, use the git stash push command like so:

bashgit stash push -- path/to/file.txt

This article will explain different ways of stashing single files and show examples of how to use each one of them.

Let's get to it 😎.

How To Stash One File In Git?

What is the stash in Git?

In Git, the stash allows a developer to shelve its changes and work on something else in the meantime.

Then, a developer can re-apply the changes from the stash to its current branch.

Stashing allows quickly switching contexts without creating new commits or branches.

How to stash a single file in Git?

There are multiple ways of stashing one file in Git.

You can use the git stash push command or an interactive stash push.

1. Using the git stash push command.

You can stash a single file using the git stash push command like so:

bashgit stash push -- path/to/file.txt

Alternatively, you can specify a stash message to retrieve the entry later easily:

bashgit stash push -m 'My message' -- path/to/file.txt

The file is now in the stash.

When ready, to retrieve it, you need to use the git stash list command. Then, use the git stash apply command to apply this file to the working area.

2. Using an interactive stash push.

Also, you can stash a single file using an interactive stash push.

bashgit stash push --patch

This command iterates through each changed file and prompts a questionnaire for each.

bashStash this hunk [y,n,q,a,d,/,s,e,?]?

Enter y for the file you want to stash and n for all the others.

Note: This method is useful when you don't have many changed files.

Final thoughts

As you can see, Git makes it easy to stash single files by providing two simple ways of doing it.

Most of the time, however, I use the git stash push method because it is the fastest.

git stash one file

Here are some other Git tutorials for you to enjoy:

Comments (0)