Skip to content

Instantly share code, notes, and snippets.

@lavelle
Last active December 19, 2015 10:59
Show Gist options
  • Save lavelle/5944589 to your computer and use it in GitHub Desktop.
Save lavelle/5944589 to your computer and use it in GitHub Desktop.
All the useful Git commands I've found (mostly from StackOverflow), in one convenient reference.

Branch from an old commit

git branch branchname ref

where ref is either a sha (abcd123) or a pointer HEAD@{5}

Undo a commit

git reset HEAD~1

--hard undoes changes to files, --soft leaves the index unchanged

Undo add

git reset HEAD file

Bonus: Undo git add . with git reset (but just don't do git add . in the first place).

Pull in changes from original repo to your fork

[git remote add upstream https://github.com/otheruser/repo.git] # First time only
git fetch upstream
[git checkout master] # If not on master already
git merge upstream/master

Restore an old file

git rev-list -n 1 HEAD -- file_path
git checkout deleting_commit^ -- file_path

Undo changes since last commit

git reset HEAD --hard
git clean -fd

Apply commits from one branch to another

git reflog              # View a list of commit SHAs
git cherry-pick abcd123 # Apply the commit with that SHA to the current branch

Edit a commit message

git commit --amend -m "New commit message"

Add files to an existing commit

git add path/to/forgotten.file
git commit --amend –C HEAD

List all files tracked by Git

git ls-tree --full-tree -r HEAD

Merge in changes to one file in another branch

# While on the branch you want to merge to
git checkout --patch other_branch file

Diff two branches

git diff --name-status branch1..branch2

Delete branches

  • Local: git branch -D branchname
  • Remote: git push origin --delete branchname
@lavelle
Copy link
Author

lavelle commented Jul 15, 2014

Delete first commit: git update-ref -d HEAD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment