Skip to content

Instantly share code, notes, and snippets.

@jednano
Last active May 31, 2023 08:23
Show Gist options
  • Save jednano/5053440 to your computer and use it in GitHub Desktop.
Save jednano/5053440 to your computer and use it in GitHub Desktop.
Common git commands in a day-to-day workflow

Git Cheat Sheet

Initial Setup

Create an empty git repo or reinitialize an existing one

git init

Click the "Fork" button at the top-right of any repository's GitHub page.

Clone the foo repo into a new directory called foo:

git clone https://github.com/<username>/foo.git foo

First, let's see a list of the repositories (remotes) whose branches you track:

git remote -v

Oh, it looks like we haven't setup upstream. Now is the time:

git remote add upstream https://github.com/<upstream_username>/<repo_name>.git
git fetch upstream

Every-day Workflow

When working on a fork, you could be switching between different branches quite commonly. As such, you generally want to stay off the master branch and work on your own feature branches so that master is always clean and you can base new branches off of it.

git switch -c <new-branch-name>

If upstream has a special develop branch or something, you can checkout that branch separately, but setup tracking so you can sync it up from time to time. Like the master branch, don't work directly on this one. Try to keep it clean.

git switch -c <new-branch-name> --track upstream/<remote-branch-to-track>

Maybe you made some progress on a branch at work, but now you want to continue work at home. In that case, you're dealing with your own fork's branch, so you'll checkout from origin.

git switch -c <new-branch-name> --track origin/<remote-branch-to-track>

If you're using the same name as a remote branch name, this can be simplified:

git switch -c <branch-name>

Use the -C option flag to force it.

First, you'll want to know what branches are available in your working directory:

git branch
  develop
  feature_x
  master

Now, you can easily switch between branches with git switch:

git switch master
git switch develop
git switch feature_x
git config --global alias.sw 'switch'
git sw master

Switch to previous branch

git switch @{-1}

credit: @MattNewbill

Not sure if you're working on a clean branch? Want to see what files have changed? Git status will show you a report.

git status

Now that you've added or modified some files, you need to stage those commits into "the staging area." Think of git commits like an array of airlock hatches on a space ship. On this space ship, you can only open the door to one airlock at a time. When you open the hatch, you can put stuff in or take stuff out at will. Not until you've closed the door have you committed those changes (git commit) and not until you hit the red button do all those hatches open up into space (git push).

You can stage inidividual files or all files at once.

git add foo.js
git add .

Maybe you accidentally staged some files that you don't want to commit.

git restore foo.js
git restore .

Commit often. You can always squash down your commits before a push.

git commit -m "Updated README"

Want to automatically stage files that have been modified and deleted, but new files you haven't told git about will be unaffected? Pass the -a or --all option flag:

git commit -am "Updated README"

The following command will undo your most recent commit and put those changes back into staging, so you don't lose any work:

git reset --soft HEAD~1

The next one will completely delete the commit and throw away any changes. Be absolutely sure this is what you want:

git reset --hard HEAD~1

Maybe you have 4 commits, but you haven't pushed anything yet and you want to put everything into one commit so your boss doesn't have to read a bunch of garbage during code review.

git rebase -i HEAD~4

An interactive text file is displayed. You'll see the word "pick" to the left of each commit. Leave the one at the top alone and replace all the others with "s" for squash, save and close the file. This will display another interactive window where you can update your commit messages into one new commit message. I like to use "f" instead of "s", because I usually work in such a way that I name my first commit appropriately from the get-go. "f" just skips the 2nd interactive file and uses the first commit message.

Push a local branch for the first time:

git push --set-upstream origin <branch>
git push

Configure Git to always push using the current branch name:

git config --global push.default current

Push a local branch to a different remote branch:

git push origin <local_branch>:<remote_branch>

Use the -f option flag to force it.

Some would say this is bad practice. Once you push something you shouldn't overwrite those changes. Instead, you're supposed to create a new commit that reverts the changes in the last one. So, technically, you shouldn't do this, but... you can?

git reset --hard HEAD~1 && git push -f origin master

Fetch changes from upstream:

git fetch upstream

Fetch changes from both origin and upstream in the same shot:

git fetch --multiple origin upstream

To be honest, I haven't used this command in quite some time. In my experience, it has created merge bubbles that have overwritten mine or others' code. For a better workflow, refer to rebasing, below.

Nonetheless, here's how you merge-in changes from origin's feature_x branch:

git fetch origin
git merge origin/feature_x

Pulling is just doing a fetch followed by a merge. If you know your branch is clean (e.g., master branch), go ahead and get the latest changes. There will be no merge conflicts as long as your branch is clean.

git pull origin/feature_x

Rebasing is a way of rewriting history. In place of merge, what this does is stacks your commits on top of commits that are already pushed up. In this case, you want to stack your commits on top of origin/feature_x:

git fetch origin
git rebase origin/feature_x

If you already have a local branch set to track feature_x then just do:

git rebase feature_x

Would you like to fetch, merge and then stack your changes on top, all in one shot? You can! If you have tracking setup on the current branch, just do:

git pull --rebase

Another great use of rebasing is just rewriting commit messages. To get an interactive text editor for the most recent commit, do:

git rebase -i HEAD~1

Now, you can replace "pick" with "r" and just change the commit message.

Perhaps you forgot to setup tracking when you pulled down a remote branch. No worries:

git config branch.<local_branch>.remote origin
git config branch.<local_branch>.merge refs/heads/<remote_branch>

Delete a local branch:

git branch -d <local_branch>

Use the -D option flag to force it.

Delete a remote branch on origin:

git push origin :<remote_branch>

Sometimes you need to stash your changes so you can be on a clean branch or maybe because you want to go back and try something before you make a commit with these changes. Here's how you do a stash:

git stash

Now, if you want to unstash those changes and bring them back into your working directory:

git stash pop

Or maybe you want to unstash your changes without popping them off the stack. In other words, you might want to apply these stashed changes multiple times. To do this:

git stash apply

For a list of stashes:

git stash list

And to apply a specific stash from that list (e.g., stash@{3}):

git stash apply stash@{3}

Tagging

git fetch --tags
git tag -a v1.0.0 9fceb02 -m "Initial release"

Where 9fceb02 represents the commit hash.

git push --tags
git tag -d v1.0.0
git push origin :refs/tags/v1.0.0

Git Bash

Once you're comfortable with what the above commands are doing, you might want to create some shortcuts for Bash or Zsh or whatever shell you're using. This allows you to work a lot faster by doing complex tasks in really short commands.

Refer to my .zshrc Gist for a good list of useful shortcuts.

@NewronAutomation
Copy link

very good one... :) thanks a lot

@mymaor89
Copy link

The best cheat-sheet ever, thanks.

@jednano
Copy link
Author

jednano commented Aug 17, 2019

Things just got more simple with git switch and git restore! But you have to build Git from source to get it. It's still experimental too, FWIW.

@swarupkumarsil
Copy link

Hi,
I am a learner in GitHub. Actually I am trying to differentiate same file with version in GitHub. But whenever I am doing any commit for a same file (committed earlier) the older commit entry is getting overridden. Please help me with the command so that all the version of a single file would available in branch and can be fetched as desired in future. Also please help with the command for fetching that particular version of that file as well. Thanks in advance.

@jednano
Copy link
Author

jednano commented Oct 18, 2019

@swarupkumarsil I'm not sure what you're asking for. Are you force pushing? If you don't force push, you'll never overwrite commits.

@Emerald-Coder
Copy link

This has been immensely helpful. Thank you so much for posting this! :)

@kbillore
Copy link

Good one!

@sureshmallel
Copy link

sureshmallel commented Apr 1, 2020

How to merge only specific commits from a pull request

  1. Pull down the branch locally. Use your git GUI or pull it down on the command line, whatever you'd like.
  2. Get back into the branch you're merging into. You'll likely do this by running git checkout master.
  3. "Cherry pick" the commits you want into this branch. Go to either the git log or the GitHub UI and grab the unique commit hashes for each of the commits that you want, and then run this command: git cherry-pick super-long-hash-here. That will pull just this commit into your current branch.
  4. Push up this branch like normal. git push origin master

CLI

git fetch origin
git checkout -b add-log-component origin/add-log-component
git checkout master
git cherry-pick COMMIT-HASH-HERE
git push origin master

@jednano
Copy link
Author

jednano commented Apr 2, 2020

@sureshmallel, you should be able to replace git checkout -b add-log-component origin/add-log-component with just git switch -c add-log-component.

@svcpowerbi
Copy link

How to use Git like single remote repo for example only one person should be able to use a file at one point of time very much like SVN or centralized repo.

@jednano
Copy link
Author

jednano commented Apr 28, 2020

I don’t understand the question.

@MattNewbill
Copy link

Can you add git checkout @{-1} to switch to previous branch? I have this page bookmarked and thats the one thing this page doesn't include that I wish it did.

@jednano
Copy link
Author

jednano commented Jun 26, 2020

Can you add git checkout @{-1} to switch to previous branch? I have this page bookmarked and thats the one thing this page doesn't include that I wish it did.

Done! Thanks for the tip, @MattNewbill! I credited your name too.

@MattNewbill
Copy link

MattNewbill commented Jun 26, 2020

@jednano thanks!!

@rudrathegreat
Copy link

thanks pretty informative. I usually use GUIs like SourceTree to do this type of stuff

@nicolehanjing
Copy link

Really good one! Thanks a lot :)

@michael-derooij
Copy link

Thanks for this, I find myself coming back to it whenever I need a refresher. Addresses the main things you'll do perfectly.

@taliavazquez
Copy link

Thank you, forking this 👯

@VivianeBusch-Wallace
Copy link

Wow, super helpful! Thank you!

@Sahu-Ayush
Copy link

Thank you!

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