Skip to content
DBDeependra Bhatta~/notes
Git & GitHub#cheat-sheet · #github · #git

Git Commands with Examples: Branch, Merge, Rebase, Stash and More

Everyday Git commands with examples: commit, diff, undo with restore, reset and revert, branches, merge conflicts, rebase, stash, tags, cherry-pick and squash.

· updated · 13 min read
ON THIS PAGE

Git commands are easier to remember when they are grouped by the problem they solve. This reference covers daily Git work by task, from committing and inspecting history to undoing changes, resolving conflicts, rebasing, stashing, tagging and squashing, with examples and screenshots from a small Docker project in a Vagrant VM. For why version control exists, the Git workflow and how to set up GitHub over HTTPS or SSH, read the first part: Git Introduction.

Basic commands

terminal
$ git clone <url>
$ git clone -b develop --single-branch https://github.com/dipen674/FDD_Website.git
$ git status
$ git add README.md
$ git add .
$ git commit -m "Add install steps to README"
$ git commit -am "Fix typo"
$ git commit --amend
$ git pull origin main
$ git push origin main
CommandWhat it does
git clone <url>Copies a remote repository to your machine
git clone -b develop --single-branch <url>Clones only one branch (here develop)
git statusShows changed, staged and untracked files
git add <file> / git add .Stages one file / all changes in the current folder
git commit -m "msg"Saves the staged changes as a commit
git commit -am "msg"Stages all tracked files and commits in one step (new files still need git add)
git commit --amendChanges the last commit's message, or adds forgotten staged changes to it
git pull origin <branch>Fetches and merges changes from the remote branch
git push origin <branch>Sends your commits to the remote branch

Remotes

terminal
$ git remote -v
$ git remote add origin <url>
$ git remote set-url origin <new-url>
$ git remote remove origin

History and inspection

terminal
$ git log
$ git log --oneline --decorate --graph
$ git show <commit_id>
$ git ls-files
  • git log --oneline --decorate --graph shows one line per commit, with branch names and a graph of merges.
  • git show <commit_id> shows the message and the exact changes of one commit.
  • git ls-files lists the files Git is tracking.

Comparing changes with git diff

git diff shows what changed between two states: the working directory, the staging area, the last commit, other commits or a remote branch.

terminal
$ git diff
$ git diff --staged
$ git diff HEAD
$ git diff -- README.md
$ git diff <commit_id> HEAD
$ git diff HEAD~1 HEAD
$ git diff origin/main
CommandCompares
git diffWorking directory with the staging area (unstaged changes)
git diff --stagedStaging area with the last commit (--cached is the same option)
git diff HEADWorking directory with the last commit (staged and unstaged)
git diff -- <path>Limits any comparison to one file or path
git diff <commit_id> HEADAn older commit with the latest commit
git diff HEAD~1 HEADThe previous commit with the latest one (HEAD^ also means "one commit before HEAD")
git diff origin/mainYour local branch with the remote main, as of the last fetch

HEAD is a pointer to the commit you are on now. origin/HEAD points to the default branch of the remote.

Undoing changes: restore, reset and revert

The right command depends on where the change currently lives.

SituationCommand
Discard edits in a file that is not stagedgit restore <file> (older form: git checkout -- <file>)
Unstage a file but keep the editsgit restore --staged <file> (older form: git reset <file>)
Undo a commit that is already pushedgit revert <commit_id>
Throw away commits that are not pushedgit reset --hard <commit_id>

git revert

git revert creates a new commit that reverses an earlier one. History is preserved, so it is safe on shared branches.

terminal
$ git revert HEAD
$ git revert <commit_id>

Git opens an editor with a default revert message. Edit it if needed, then save and close the editor.

git reset

git reset moves the branch pointer back to an older commit. The mode determines what happens to the changes from the dropped commits:

ModeCommits after the targetStaging areaWorking directory
--softremoved from historychanges stay stagedkept
--mixed (default)removed from historyclearedkept
--hardremoved from historyclearedchanges lost
terminal
$ git reset --hard <old_commit_id>

Branches

The Gitflow branch model (main, develop, feature, release, hotfix) is explained in Git Introduction. The commands below list, create, switch, rename and delete branches:

terminal
$ git branch
$ git branch -a
$ git switch develop
$ git switch -c feature/login
$ git branch -m old-name new-name
$ git branch -m new-name
$ git branch -d feature/login
$ git push origin --delete feature/login
CommandWhat it does
git branchLists local branches; * marks the current one
git branch -aLists local and remote branches
git switch <branch>Switches to an existing branch (older form: git checkout <branch>)
git switch -c <branch>Creates a branch and switches to it (older form: git checkout -b <branch>)
git branch -m <old> <new>Renames a branch from another branch
git branch -m <new>Renames the current branch
git branch -d <branch>Deletes a merged local branch (-D forces it)
git push origin --delete <branch>Deletes a branch on the remote

Merging

git merge <branch> brings the commits of <branch> into the branch you are on.

If the current branch has no new commits of its own, Git performs a fast-forward merge: it moves the branch pointer forward and creates no merge commit. Example: develop has commits C and D on top of main:

TXTPlain text
A -- B  (main)
      \
       C -- D  (develop)
 
$ git switch main
$ git merge develop
 
A -- B -- C -- D  (main, develop)

With --no-ff (no fast-forward), Git always creates a merge commit, even when a fast-forward is possible:

terminal
$ git merge --no-ff develop
TXTPlain text
A -- B ------------ M  (main)
      \            /
       C -- D -----    (develop)

M is a merge commit that bundles the changes from develop, so the history records that these commits came from a separate branch. Many teams use --no-ff for exactly this reason.

Merge conflicts

A merge conflict happens when Git cannot combine two changes on its own. Common causes:

  • Two branches change the same line of the same file.
  • One branch edits a file while another branch deletes it.

In my lab, a conflict appeared when two branches changed the same LABEL line in a Dockerfile:

Merge conflict in a Dockerfile in VS Code: HEAD has LABEL version 1.4, incoming develop has LABEL version 1.1

Git marks the conflict in the file:

  • Between <<<<<<< HEAD and ======= is the current change (the branch you are on).
  • Between ======= and >>>>>>> develop is the incoming change (the branch you are merging).

To resolve the conflict, edit the file to the content you want and delete all three marker lines. VS Code also offers inline actions such as Accept Current Change and Accept Incoming Change.

Dockerfile after resolving the conflict: markers removed and a single LABEL version line left

Stage the file and commit to complete the merge:

terminal
$ git add Dockerfile
$ git commit -m "Resolve version label conflict"

To return to the state before the merge, run git merge --abort. Merging frequently keeps conflicts small.

Rebase

git rebase moves your branch so that it starts from the tip of another branch. Git replays each of your commits on top of the new base, creating new commits. The result is a linear history without merge commits.

terminal
$ git switch feature/login
$ git rebase main

If a conflict appears, resolve the file as you would for a merge conflict, stage it, and continue or abort:

terminal
$ git add <file>
$ git rebase --continue
$ git rebase --abort

--continue proceeds to the next commit. --abort stops the rebase and restores the branch to its previous state.

Stash

git stash saves uncommitted changes and leaves a clean working directory. Use it to switch tasks or ship an urgent fix when the current work is not ready to commit.

terminal
$ git stash
$ git stash push -m "half-done compose changes"
$ git stash -u
$ git stash list
$ git stash show stash@{1}
$ git stash apply stash@{1}
$ git stash pop
$ git stash drop stash@{1}
$ git stash clear
$ git stash branch newchanges
CommandWhat it does
git stashSaves changes to tracked files and cleans the working directory
git stash push -m "msg"Same, with a message (git stash save "msg" is the older, deprecated form)
git stash -uAlso stashes untracked files
git stash listLists all stashes with index and message
git stash show stash@{1}Shows a summary of one stash (add -p for the full diff)
git stash apply stash@{1}Applies a stash and keeps it in the list
git stash popApplies the latest stash and removes it from the list
git stash drop [stash@{1}]Deletes the latest stash, or the one given
git stash clearDeletes all stashes
git stash branch <name>Creates a branch from the commit where the stash was made, applies the stash, and drops it if that works

The newest stash is always stash@{0}. When you stash again, older entries move down to stash@{1}, stash@{2} and so on. This stash@{n} form is called reflog syntax.

git stash list in a Vagrant VM showing stash@{0} and stash@{1}, both WIP on main

After git stash branch, the changes live on the new branch. Commit them there and merge the branch into main when ready.

Tags

A tag is a name that points to one commit, usually a release such as v1.0.1. Deployment tools often use tags to select the version to deploy.

Git has two kinds of tags:

  • Lightweight tag: a name that points to a commit, with no extra metadata.
  • Annotated tag: also stores the author, date and a message. Use these for releases.
terminal
$ git tag v1.0
$ git tag -a v1.1 -m "Release 1.1"
$ git tag -a v0.8-alpha <commit_id> -m "Alpha build"
$ git tag -a -f v0.8-alpha <commit_id>
$ git tag --list
$ git diff v1.0 v1.1
$ git tag --delete v1.0
$ git push origin v1.1
$ git push origin --tags
$ git push origin --delete v1.1
CommandWhat it does
git tag <name>Creates a lightweight tag on the current commit
git tag -a <name> -m "msg"Creates an annotated tag (-m alone also makes it annotated)
git tag -a <name> <commit_id>Tags an older commit
git tag -a -f <name> <commit_id>Moves an existing tag to another commit
git tag --listLists all tags
git diff <tag1> <tag2>Shows the changes between two tags
git tag --delete <name>Deletes a local tag
git push origin <name>Pushes one tag (tags are not pushed by git push alone)
git push origin --tagsPushes all tags
git push origin --delete <name>Deletes a tag on the remote (use refs/tags/<name> if a branch has the same name)

Cherry-pick

git cherry-pick copies the changes of one or more specific commits onto the current branch. Merge and rebase bring in every commit of the other branch; cherry-pick takes only the commits you name. A typical use is pulling a single fix from a teammate's branch.

terminal
$ git cherry-pick <commit_id>
$ git cherry-pick <commit_id_1> <commit_id_2>
$ git cherry-pick -n <commit_id>

-n (--no-commit) applies the changes without committing them, so you can adjust them first.

Picking several commits can cause conflicts. Resolve the files as for a merge conflict, then continue, skip the commit, or abort:

terminal
$ git add .
$ git cherry-pick --continue
$ git cherry-pick --skip
$ git cherry-pick --abort

Squash

Squashing combines several commits into one. It cleans up a feature branch full of small commits ("fix", "fix again") that clutter the history. The code changes stay the same; only the commits are combined.

Squash a whole branch into one commit while merging:

terminal
$ git switch main
$ git merge --squash feature/login
$ git commit -m "Add login feature"

git merge --squash stages all the changes without committing, so the final git commit is required.

To squash the last few commits on your own branch, use an interactive rebase:

terminal
$ git rebase -i HEAD~3

In the editor, keep pick on the first commit and change the others to squash (or s). As with any rebase, do this only on commits you have not shared.

Key takeaways

  • git restore undoes local edits, git revert safely undoes pushed commits, and git reset --hard is only for unpushed work.
  • Fast-forward merges keep history linear; --no-ff keeps a merge commit that shows where a branch came in.
  • Resolve a conflict by editing the file, removing the markers, then git add and commit (or --continue during rebase and cherry-pick).
  • Rebase and interactive squash rewrite history: use them only on your own branch.
  • git stash pop applies and removes a stash; git stash apply keeps it.
  • Use annotated tags for releases, and push them with git push origin <tag> or --tags.