LoginSignup
0
0

More than 3 years have passed since last update.

Gitting out of trouble!

Last updated at Posted at 2020-12-03

Getting in and out of bad situations with Git

Git can be hard and it's easy to make mistakes.

Here are some bad situations I've gotten myself into recently, and how I got myself out of them.

Go back in time

I did something terrible. Can I go back?

git reflog

you will see a list of every thing you've done in git, across all branches!

each one has an index HEAD@{index} find the one before you broke everything

git reset HEAD@{index}

magic time machine
Screen Shot 2020-12-03 at 15.49.08.png
You can use git reflog to:

  • Get back work you accidentally deleted.
  • Remove something you tried that broke the repo.
  • Recover after a bad merge, or just to go back to a time when things worked.

Rewrite history

I committed but need to make a change last commit message

git commit --amend

I committed but need to make a small change to the last commit

make your change

git add . # or add individual files
git commit --amend --no-edit

now your last commit contains that change!

Never amend public commits!

Rewrite history: interactive rebase

I committed but need to make a bigger change: interactive rebase!

git rebase 

git rebase re-applies commits, one by one, in order, from your current branch onto another.

Rebase accepts --interactive (-i for short) option, which will open an editor with a list of the commits which are about to be changed. This list accepts commands, allowing the user to edit the list before initiating the rebase action.

I made a few commits but want to combine them into one

git rebase -i HEAD~4

pick 07c5abd Commit message x
pick de9b1eb Commit message y
pick 3e7ee36 Commit message z
pick fa20af3 git interactive rebase, squash, amend

Commands
s, squash = use commit, but meld into previous commit

I give up

Reset the state of your repo to be the same as the remote repo (Beware: destructive and unrecoverable action!)

get the latest state of origin

git fetch origin
git checkout master
git reset --hard origin/master

delete untracked files and directories

git clean -d --force
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0