Saturday, September 21, 2024
Google search engine
HomeGuest BlogsHow to Git Stash Specific Files

How to Git Stash Specific Files

Introduction

Git stash allows users to save their uncommitted files and work in progress to a local stash and go back to the last commit done on the branch (the HEAD). By stashing their work, developers can shift their focus to something else and later resume working on the unfinished code.

Stashing specific files is useful because it allows developers to select and differentiate between files they need to work on and the ones that are ready for committing.

In this tutorial, you will learn to stash a specific file in Git.

How to stash a specific file in Git?How to stash a specific file in Git?

Prerequisites

How to Git Stash a Specific File?

The git stash command stashes all tracked files in the current working directory. Stashing a specific file requires the additional push option along with the file name.

Use the following syntax to stash a specific file:

git stash push [file]

For example:

Stashing a specific file in Git.Stashing a specific file in Git.

Running the command stashes only the specified readme.md file, while any other files that may have been changed remain unstashed.

To further customize the stashed work, use one of the following options:

Add a Message

Specify the -m flag and add a custom message to the stashed file to ensure you later know what the change involved. The syntax is:

git stash push -m "message" [file]

For example, the following command stashes the file and adds the following message:

git stash push -m "Made edits to the readme file" readme.md
Stashing a single file in Git with a description.Stashing a single file in Git with a description.

Interactive Stashing

The --patch (-p) option allows users to interactively stash parts of files called hunks. To stash partial changes, run the following command:

git stash push --patch

The command initiates an interactive mode, prompting you to select an action for each hunk iteration. Press one of the following keys to operate the prompts:

  • y – Stash the current hunk.
  • n – Skip the current hunk.
  • q – Abort stashing.
  • a – Stash the current hunk and all later ones in the file.
  • d – Skip stashing all hunks in the specified file.
  • / – Search for a hunk.
  • s – Split the current hunk into smaller hunks.
  • e – Manually edit the current hunk.

For example, press y and Enter to stash a hunk:

Interactively stashing hunks of files in Git.Interactively stashing hunks of files in Git.

Check if the files have been stashed by running:

git stash list
Listing existing stashes.Listing existing stashes.

The output shows all the stashes in the ref and the stash message.

Conclusion

This tutorial showed how to stash a specific file in Git. For more Git tutorials, see how to use Git, learn to use Git bash, or learn to work with Git tags.

Was this article helpful?
YesNo

RELATED ARTICLES

Most Popular

Recent Comments