Como recuperar uma modificacao apos um “git reset –hard HEAD^”

Sem querer voce executou um “git reset –hard HEAD” para remover o ultimo patch que voce criou, só que voce esqueceu de salvar o patch e gostaria de ter novamente as modificacoes que voce fez.

Nao precisa comecar a chorar, basta seguir esta dica:

$ echo “added new file” > file2
$ git add file2
$ git commit -m ‘added file2’
Created commit f6e5064: added file2
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 file2

$ git reset –hard HEAD^
HEAD is now at 1a75c1d… added file1

Now to send it to server execute:
$ git push –force origin master

$ cat file2
cat: file2: No such file or directory

$ git reflog
1a75c1d… HEAD@{0}: reset –hard HEAD^: updating HEAD
f6e5064… HEAD@{1}: commit: added file2

$ git reset –hard f6e5064
HEAD is now at f6e5064… added file2

$ cat file2
added new file


Update: This error could happen:
$ git push
To git@
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to ‘git@’
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes before pushing again. See the ‘Note about
fast-forwards’ section of ‘git push –help’ for details.

In this case use this command:
$ git push –force