Git Commands Cheat Sheet
The purpose of this guide is to summarize the most common git commands into a simple cheatsheet, along with short descriptions, instructions and examples on how to use them. It’s based off of the Pro Git book (available here), and of many other online articles and tutorials.
This article assumes some basic Git knowledge.
Basics
Starting a Git Repository
To initialize a repository in an existing directory, use:
$ git init
To clone an existing repo, use:
$ git clone <url> [<directoryName>]
This will create a new directory (within your current directory) that will contain a local copy of the Git repository. You only need <directoryName> if you want to specify the name of this directory.
Checking Branch Status
To check the status of the current branch, use:
$ git status [-s]
The optional -s flag stands for short, and will give you a more simplified output, such as:
M README
MM Makefile
A class.cpp
M class.h
?? LICENSE.txtHow to read:
The right-hand column indicates the status of the working directory and the left-hand column indicates the status of the staging area. For example:
READMEwas modified but not added to the staging area.Makefilewas modified, added and modified again.class.hwas modified and staged.LICENSE.txtis not being tracked.
Checking File Diffs
Using git status will show you which files were changed, but not what exactly changed in these files. If you want to see file diffs of the current branch, use:
$ git diff [--staged]
With --staged, you’ll see what has been staged since your last commit. Without --staged, you’ll see what has been modified but not staged.
Note: --staged and --cached are equivalent, so you can use --cached too.
Adding Files
To add files to the staging area, type:
$ git add <files>
Removing Files
To make Git stop tracking specific files, use:
$ git rm [-f] [--cached] <files>
You need -f (or --forced) if the files you’re removing have been modified and staged. This prevents you from accidentally removing data that Git hasn’t snapshotted yet (and thus could not recover if needed).
You need--cached if you want to keep those files in your work directory. Without it, the files will also be removed from your work directory (which, in many cases, is what you want).
Renaming Files
To rename a file that is tracked by Git, use:
$ git mv oldName newName
Note that this is equivalent to:
$ mv oldName newName
$ git rm oldName
$ git add newNameCommitting Changes
To commit your changes (the files in the staging area), use:
$ git commit [-a] [-m <message>]
If you use -a, git will add all tracked files to the staging are before committing.
If you use -m <message>, git will use that message for the commit. If you don’t, git will launch an editor and ask you to enter a commit message.
Viewing the Commit History
To see your commit history, use:
$ git log
You can also use many options to customize the formatting:
- With
-p(or--patched), the history will include the file diffs introduced in each commit. - With
--stat, Git will give you abbreviated stats for each commit, such as which files were added, changed, or removed. - With
--graph, Git will visually display your branch and merge history. - With
--oneline, each commit will be printed in a single line. - With
--pretty=format:"<format>", you can specify the format and the information you want to be printed out for each commit. Since there are many different formats, they won’t be covered in this article.
There’s also options that filter or limit the entries to be printed out:
- If you use
-<number>you can specify how many entries you want to see. - If you use
-S <string>, Git will only show the commits that changed the number of occurrences of that string within the tracked files. This can be useful to see which commits changed references to certain classes, functions, etc. - You can use
--grepto show commits with messages containing a given string. - You can use
--since(or--after) and--until(or--before) to only show entries between those dates.
These are just a few of the options available. Check online, or in the Git documentation, for more options and examples on how to use them.
Undoing Mistakes
Undoing init
If you used $ git init by accident, or in the wrong directory, you can “undo” it by going to the same directory where you did the init, and using:
$ rm -rf .git
If you accidentally enter $ rm -rf by itself, all of the files in your system will be deleted. For that reason, I recommend you copy & paste this command!
Fixing the Last Commit
To fix the most recent commit, you can use:
$ git commit --amend [-m <message>]
This can be useful for adding changes to your commit that you forgot about, or changing the last commit message with -m <message>.
It’s important to note that this command replaces the old commit with a new commit. For this reason, you should always avoid using this with commits that have been pushed to a remote repo (which is covered later in this article).
Unmodifying Files
To unmodify a modified file (reset it to its state from the last commit), use:
$ git checkout -- <files>
This does not affect files in the staging area, only files that are modified but not staged. Be careful because there’s no way to recover the changes once you undo them.
Unstaging Files
To unstage files, use:
$ git reset HEAD <files>
Note: these files will just be unstaged. That is, their changes will be kept in the working directory.
Going Back in Time
The git reset command is also useful when you want to go back in time a few commits. There are some options you’ll want to get familiar with:
$ git reset --soft <commit>: the branch (andHEAD) will now point to the specified commit, but the index (staged files) will be kept. In other words, all the commits back until the specified one (non-inclusive) will disappear, BUT all the changes you’ve made since then will be kept in the current state of your branch. This is a good idea for squashing commits.$ git reset --hard <commit>: the branch (andHEAD) will now point to the specified commit, but the changes won’t be kept. In other words, your branch will go back until that commit, but all the commits and changes (staged and unstaged) that followed it will be gone.
Since using git reset manipulates commits, please avoid using this on commits that have already been pushed remotely!
Remote Repositories
Git repos/projects are usually hosted on some server(s), often to allow for collaboration. Repositories hosted on servers are referred to as remote repositories. When you clone a repo, Git saves the server you cloned from as a remote repository and calls it origin by default.
Listing Your Remotes
To see a list of your remotes, use:
$ git remote [-v]
If you use -v, the URL and permissions of each remote will be displayed in addition to its handle.
Adding New Remotes
To add a new remote repository, use:
$ git remote add <name> <url>
Fetching from Remotes
While multiple remotes work on the same project, they might contain different information (depending on who’s working with that remote or what it’s intended to be for), which is usually merged together in the future.
To fetch information from a remote (since you cloned or last fetched), use:
$ git fetch <remote>
You now have a local copy of that remote’s working tree, whose branches you can refer to as <remote>/<branch>. Branches will be covered later in this article, so don’t worry if you don’t understand them yet!
Pushing to Remotes
To push a branch to a remote, use:
$ git push <remote> <branch>
This only works if your work is up to date with that remote. That is, if nobody has pushed their work to that remote since you last fetched/pulled. If that’s not the case, your push will be rejected, and you’ll have to fetch from remote and merge the work into yours before attempting to push again.
Inspecting a Remote
To inspect a remote (view its access permissions, and list its branches with and their tracking information), use:
$ git remote show <remote>
Editing Remote References
To rename a remote, use:
$ git remote rename <oldName> <newName>
To remove a remote, use:
$ git remote remove <remote>
These two commands have the side effects you would expect: renaming a remote updates the way you reference its branches (<remote>/<branch>) with the new name, and removing a remote deletes the references to its branches and to itself.
Branching
Branching is a Git feature that allows you to organize the way in which you split your work (build features, fix bugs and make changes) by diverging from your main workflow into more purpose-specific workflows that are independent from each other. These are often merged into the branch that contains the main workflow (usually the master branch).
You can picture a Git repo as a tree where each node is a commit and each branch is a pointer to a node.
Creating Branches
There’s two main ways to create a branch. If you just want to create one, use:
$ git branch <branchName>
This will make an exact copy of the state of the branch where the new branch was created from, including uncommitted changes.
To switch to that (or any) branch, use:
$ git checkout <branchName>
Git uses a pointer called HEAD that points to the branch you’re currently working with. When you switch to a different branch, Git simply updates HEAD to point to it.
A nice shortcut to make a new branch AND switch to it is the following:
$ git checkout -b <branchName>
Local branches often track branches in a remote repo, which is where they git pull from and git push to. You can directly set up this relationship when you create the branch, by using:
$ git checkout -b <localBranchName> <remote>/<remoteBranchName>
Note that localBranchName and remoteBranchName are typically the same, such as in the case of master and origin/master, but they don’t need to be. If, for example, you’re working with a team or a company that has a convention for how you need to name your branches, you can do that with the remoteBranchName, and name localBranchName whatever you want. After all, you’ll be the only one using it ;)
Deleting Branches
To delete a branch, use:
$ git branch -d <branchName>
If you haven’t merged this branch yet, Git won’t let you delete it unless you use the forced version of the above command:
$ git branch -D <branchName>
This keeps you from accidentally deleting a branch whose changes you haven’t integrated yet.
Merging Branches
To merge a branch into another, first you need to checkout the branch you’re merging into, and then use:
$ git merge <branch>
Let’s say we have a master branch and a bugFix branch. Merging bugFix into master would look like this:
$ git checkout master
$ git merge bugFixMerge Conflicts
You’ll often run into merge conflicts, which usually happen when the two branches you want to merge together are adding/modifying the same files. When this happens, the merge commit won’t be created until the conflicts are resolved. The git status command will list these files when applicable.
Git will join the conflicting files together and mark where these conflicts are happening so you can find them more easily. Imagine we have a file hi.cpp that had conflicts. Somewhere in the file, the conflict might look like this:
<<<<<<< HEAD:hi.py
print("Hi, I like pizza!")
=======
print("Hi, I like beer!")
>>>>>>> bugFix:hi.pyThis means that this block of code differed in your current branch (where HEAD is currently at) from the branch you want to merge in. You can handle this however you want. In this case, for example, I would replace it with:
print("Hi, I like pizza and beer!")Instead of going over these and changing them manually, you can also choose to keep a file from either branch, discarding the other conflicting version.
To keep the file version of the branch you’re in, use:
$ git checkout --ours <filename>
To keep the file version of the branch you’re merging from, use:
$ git checkout --theirs <filename>
Once you’ve solved your merge conflicts with either technique, you’ll want to stage (git add) these files and finalize the merge commit with the usual git commit command.
Listing Branches
To see a list of your branches, use:
$ git branch [-v]
This will display a list of your branches, with an asterisk * next to the name of the branch you’re in. If you use -v, the last commit message of each branch will be displayed as well.
Another option you can use with this command is --merged or --no-merged. Use these to see list the branches you have or haven’t merged with a specific branch (or with the branch you’re in, if <branchName> is omitted):
$ git branch (--merged/--no-merged) [<branchName>]
Stashing
Git provides you with a way to store your current tracked changes (modified and staged files) into a stack that is visible from all of your branches, so you can work on something else and re-apply them later. This allows you to, for example, switch from branch A to branch B without potentially having to commit some changes in branch A.
Stashing Changes
To stash the changes of your current branch, use:
$ git stash
This will group all of your tracked (and uncommitted) changes, push them to the stack, and clean your working directory. That is, revert these files to what they looked like before these changes. It is now safe to switch to other branches, do some other work, and then come back and apply the stashed changes if you desire.
Note that this is equivalent to:
$ git stash push
Listing Stashes
To view the list of stashes you’ve pushed, use:
$ git stash list
This will list all of your previous stashes (that you haven’t popped yet) in chronological order, with the most recent on top. Each stash is given an id of the form stash@{i}, where i is its index in the stack. The most recent stash has an index of 0.
Applying Stashes
To apply a stash, use:
$ git stash apply [<stashID>] [--index]
You need <stashID> if you want to specify an older stash. If you don’t, Git will use your most recent stash by default.
You need --index if you want your previously staged files to be applied as staged again, and your previously modified files to be applied as modified. Otherwise, Git will default all of your applied changes to modified.
Dropping Stashes
Applying stashes doesn’t take them off of the stack. To do so, use:
$ git stash drop [<stashID>]
If a <stashID> is not specified, Git will use the most recent by default.
Note that all stash IDs greater than the one you just dropped (if any) will be updated.
Popping Stashes
Git provides you with a useful way to both apply and drop a stash in one command:
$ git stash pop [<stashID>] [--index]
This will take the specified stash, apply its changes and drop it from the stack.
If a <stashID> is not specified, Git will use the most recent stash by default.
The rules for --index are the same as when you use git apply.
