simonewebdesign

Git cheat sheet

Git is an awesome tool for developers, but can be a bit hard to grasp at a first glance. Fortunately, the concepts you need to learn to be immediately productive are very few: I’ll briefly illustrate them in this Git cheat sheet.

1. Basics

# start a Git repository from scratch
$ git init

# copy an existing repository into the current directory
$ git clone https://github.com/username/repository.git

$ git status  # check current status

2. Snapshotting

# Add files to staging area
$ git add filename  # add a single file
$ git add .         # add all files, but not deleted ones
$ git add --all     # add everything

# Stashing takes the current state of the working directory and
# puts it on a stack for later
$ git stash        # add current changes to the stack
$ git stash list   # see what's in the stack
$ git stash apply  # bring back the saved changes

3. Committing

$ git commit            # open the text editor (usually vi)
$ git commit -a         # automatically stage modified files
$ git commit -m "foo"   # commit with message "foo"
$ git commit -am "foo"  # both stage files and commit with message "foo"

# View commits log (in a pretty way)
$ git log --oneline --decorate --graph

4. Managing remotes

$ git remote add origin https://github.com/user/repo.git
# You can also add your GitHub username and password on the remote URL:
$ git remote add origin https://user:password@github.com/user/repo.git
$ git remote rm origin  # removes the `origin` remote

5. Pushing

$ git push -u origin master
# -u here tells git to remember the parameters
# so that next time we can simply run:
$ git push

6. Branching

$ git checkout -b new_branch
# -b is to checkout and create a branch at the same time.
# This is the same thing as doing:
$ git branch new_branch
$ git checkout new_branch

7. Merging

$ git checkout master       # return to master branch
$ git merge --no-ff foobar  # merge `master` branch with `foobar` branch
$ git branch -d foobar      # delete branch locally
$ git push origin :foobar   # delete branch on the origin remote

8. Tagging

$ git tag -a v1.3.37               # tag the HEAD (most recent commit)
$ git tag -a v0.6b f49a23c         # tag the commit with SHA `f49a23c`
$ git tag -a v4.2 -m "jelly bean"  # append a message

That’s all, folks. I know I could have explained much more every single command, but that’s not the point of this article. I just wanted to give you a quick-start pragmatic reference; in fact, these are the commands I personally use more frequently.

Do you think some very useful commands are missing in this cheat sheet? Leave a reply.

  • Update March 5th: added tagging.
  • Update April 23rd: just made some “refactoring” and added git stash.
  • Update Dec 3rd: I’ve updated the “merging” section with the command for deleting the remote branch as well. I’ve also added the --no-ff option, that disables fast-forwarding (reason explained here).
View this page on GitHub