1

It was suggested to me that I could restore my code to the way it is in the origin repository using this command:

git reset --soft HEAD~1

I looked for information on this but didn't find anything that explained

HEAD~1

What does the ~1 part of the command do?

phd
  • 82,685
  • 13
  • 120
  • 165
Alan2
  • 23,493
  • 79
  • 256
  • 450
  • Might be useful: https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection – raina77ow Feb 22 '19 at 12:37
  • I don't feel like the "possible duplicate" fully answers this question - yes, it does explain what `~1` is, but the suggested command in the question is also likely not the right choice, so I feel that the question deserves being covered in more detail. – Jan Krüger Feb 22 '19 at 12:50
  • https://stackoverflow.com/search?q=%5Bgit%5D+HEAD+tilde – phd Feb 22 '19 at 13:34

1 Answers1

3

The official documentation for this syntax is in the gitrevisions manpage.

HEAD~1 means: go back 1 commit from HEAD, using the first parent (most commits have only one parent, so this syntax covers most cases where you want to go further back).

HEAD~1 is so common that it can also be shortened to HEAD~.

It's important to understand, though, that HEAD has little to do with the state of the origin repository! HEAD~1 will happen to match the current state of the origin in these cases:

  • You just pulled (merged) from the origin, and it created a merge commit (prompted for a merge commit message).
  • You were up-to-date with the origin and then made a single new commit on top.

In other cases you would probably use @{upstream} which references the upstream of your current branch (also documented in the gitrevisions manpage).

Finally, --soft often isn't the right choice, either. It means that all your changes will be preserved in the working tree and index. Your files won't change at all, and git status will show all the changes as "to be committed".

If you want to basically hit the reset button and irrevocably destroy all committed and uncommitted changes you have locally compared to the upstream, I recommend this:

git reset --hard @{upstream}
Jan Krüger
  • 17,870
  • 3
  • 59
  • 51