You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The "Oh no I should have been working in a branch" Trick
# takes staged changes and 'stashes' them for later, and reverts to HEAD.
$ git stash
# creates new branch and switches to it, then takes the stashed changes and stages them in the new branch. fancy!
$ git stash branch new-branch-name
The "I forgot something in my last commit" Trick
# first: stage the changes you want incorporated in the previous commit# use -C to reuse the previous commit message in the HEAD
$ git commit --amend -C HEAD
# or use -m to make a new message
$ git commit --amend -m 'add some stuff and the other stuff i forgot before'
The "Oh crap I didn't mean to commit yet" Trick
# undo last commit and bring changes back into staging (i.e. reset to the commit one before HEAD)
$ git reset --soft HEAD^
The "That commit sucked! Start over!" Trick
# undo last commit and destroy those awful changes you made (i.e. reset to the commit one before HEAD)
$ git reset --hard HEAD^
The "I have merge conflicts, but I know that one version is the correct one" Trick, a.k.a. "Ours vs. Theirs"
# in master
$ git merge a_branch
CONFLICT (content): Merge conflict in conflict.txt
Automatic merge failed; fix conflicts and then commit.
$ git status -s
UU conflict.txt
# we know the version of the file from the branch is the version we want.
$ git checkout --theirs conflict.txt
$ git add conflict.txt
$ git commit
# Sometimes during a merge you want to take a file from one side wholesale.# The following aliases expose the ours and theirs commands which let you# pick a file(s) from the current branch or the merged branch respectively.## N.b. the function is there as hack to get $@ doing# what you would expect it to as a shell user.# Add the below to your .gitconfig for easy ours/theirs aliases. # ours = "!f() { git checkout --ours $@ && git add $@; }; f"# theirs = "!f() { git checkout --theirs $@ && git add $@; }; f"
Other useful commands
The "Cleanup Local Branch Mess" Trick
# Delete local branches that have been merged into HEAD
$ git branch --merged | grep -v '\\*\\|master\\|develop'| xargs -n 1 git branch -d
# Delete local branches that have been merged into origin/master
$ git branch --merged origin/master | grep -v '\\*\\|master\\|develop'| xargs -n 1 git branch -d
# Show what local branches haven't been merged to HEAD
$ git branch --no-merged | grep -v '\\*\\|master\\|develop'