avatar

Andres Jaimes

Undoing the Last Git Commit

By Andres Jaimes

- 2 minutes read - 222 words

A command so important, it deserves its own page:

git reset --soft HEAD~1

The previous command undoes the last commit to git. I think this is one of those commands that I have typed many times during the last year. It’s very important to know which branch we currently are on, but sometimes excitement (or stress) may make us forget checking it.

If this is not enough, then we can reset our branch to master like this: (this will lose all our changes):

git checkout master
git reset --hard origin/master

Search for commited code in git history

A useful command to search for a specific piece of text in previous commits:

git grep <regex> $(git rev-list --all)

Source: https://stackoverflow.com/a/2929502/19787392

Display the current git branch on the prompt

Related to this topic, I have a custom prompt that shows a random smiley and the current git branch to the prompt. If we are using bash, we can add the following lines to ~/.bash_profile. Restart the terminal or reload the changes by using source .bash_profile.

HAPPY=(🙂 🙃 🤓 😎)

parse_git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

emoticon() {
  echo ${HAPPY[$RANDOM % ${#HAPPY[@]}]}
}

export PS1="\$(emoticon) \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

alias ls='ls -F'

This prompt looks like this:

🙂 some-directory (master) $

For non-git directory it hides the branch part.