by BehindJava

What is Git Stash and Git Squash

Home » interview » What is Git Stash and Git Squash

In this tutorial, we are going to learn about Git Stashing and Git squashing.

Git Stashing

Stash is a section of git into which once the files are pushed git cannot access them.

  • To stash all the files present in the stagging area.

    git stash
  • To stash all files present in stagging area and untracked section.

    git stash -u
  • To stash all files present in stagging area, untracked section and .gitignore.

    git stash -a
  • To see the list of stages.

    git stash list
  • To unstash a latest stash.

    git stash pop
  • To unstash an older stash.

    git stash pop stash@{stashno}

Git squash

This is the process of merging multiple commits and making it look like a single commit. This can be done using the git rebase command.

  1. Create a commit history.

    a --> b --> c --> d --> e --> f
    HEAD is pointing ti f commit

Note: a commit is called as the “initial commit” and it cannot be squashed.

  1. In the above scenario we can squash only a max of 5 commits 2 To squash.

    git rebase -i HEAD~5
  2. This will open the top 5 commits in vi editor For which ever commits we want to perform a squash operation remove the word “pick” and replace it with “squash”.
  3. Check the commit history.

Git rebase can also rearrange the commit history order

  1. Create a commit history.

    a --> b --> c --> d --> e --> f
    HEAD is pointing to f commit
  2. To rearrange the commit history order.

    git rebase -i HEAD~5
  3. Rearrange the commits in whatever order that we want.
  4. Check the commit history now.

    git log --oneline