blog

Photo of Elephant by Nam Anh on Unsplash

17 Useful git Commands That I Can’t Remember

by

I’m thankful for git for many reasons, like fast commits, offline history browsing, and cheap branching. But one complaint I have is the illogical naming and arguments of git commands.

I’ve long kept a list of useful but hard to remember commands in a notepad.  Here’s my list, roughly sorted by most frequently used.  Careful with the dangerous commands at the bottom.

Common git commands

Tag and share a release

git tag -a release/1.0.0b1 -m "1.0.0b1 release"
git push --tags
git show-ref --tags 1.0.0b1

Undo the last local commit

git reset --soft HEAD^
git reset HEAD .

Stash only unstaged files

git stash save --keep-index

Stage all files, included deletions

git add -u

Revert a commit

If a commit has already been shared publicly, this creates a changeset that reverses the commit.

git revert COMMITHASH

Undo a merge

git merge --abort

View the url of a remote repository

git remote -v

or

git remote show origin

Show the current branch name

git rev-parse --abbrev-ref HEAD

Push a local branch

git push origin BRANCH

List remote branches

git branch -r

(or -a for all branches)

Delete a remote branch

git push origin :BRANCH

Delete local tracking branches

Fixes a common error about deleting a branch from origin when another user has already deleted that remote branch.

git fetch -p origin

Compare commits on two branches

git diff BRANCH1..BRANCH2

Compare commit messages on two branches

git log --cherry-mark --oneline BRANCH1..BRANCH2

Delete a tag

¡dangerous! This rewrites the public repository and breaks other users’ clones if they have already pulled this tag.

git tag -d 12345
git push origin :refs/tags/12345

Move commits to a new branch

¡dangerous! You will lose uncommitted work. Only works for moving commits to a new branch. Moves all commits not on BRANCHNAME to NEWBRANCHNAME. Hat tip to sykora’s SO answer.

git branch NEWBRANCH
git reset --hard origin/BRANCH
git checkout NEWBRANCH

Delete untracked files

¡dangerous! This permanently deletes untracked files.  But the -n flag does a dry-run to help catch mistakes.

git clean -fn

Git alias

Git also provides an alias feature, which could be used to create more memorable commands.  Here’s my simplistic set of aliases in ~/.gitconfig , mostly geared towards reducing typing for common commands:

[alias]
    st = status
    ci = commit
    co = checkout
    df = diff
    lg = log -p

+ more