Skip to content

Instantly share code, notes, and snippets.

@michael-milette
Last active September 19, 2023 05:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michael-milette/9bc207e0495605ea3e6a67ee266abf60 to your computer and use it in GitHub Desktop.
Save michael-milette/9bc207e0495605ea3e6a67ee266abf60 to your computer and use it in GitHub Desktop.
Cheatsheet: Tips and Tricks for using Git

Cheatsheet: Tips and Tricks for using Git

Table of Contents

Lots of Git Tips

Repositories

Shallow clone (quick)

git clone https://github.com/username/reponame.git --branch branchname --single-branch --depth 1

Un-shallow

Revert shallow clone into full clone.

git fetch --unshallow
git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
git fetch origin

Remote Repositories

List remotes

git remote -v

How to Set an Upstream Without Push

git branch --set-upstream-to origin/my_branch
git branch -u origin/my_branch

How to Rename a Remote

git remote rename upstream origin

Add a remote

git remote add upstream https://github.com/username/reponame.git

Change URL of existing remote

git remote set-url origin new.git.url/reponame.git

List all branches on remote repository

git remote show origin

Stash

Stash specific files (as of Git 2.13)

git stash push -- [filepaths]
- or -
git stash push -m "message" [filepath]

Stash hunks of lines interactively

git stash -p

Stash with custom message

git stash save "Your custom message"

See recent stash:

git stash show -p
git stash show -p stash@{0}

git stash list
git stash show -p stash@{1}

git stash drop

Recover dropped stash in Git

https://gist.github.com/joseluisq/7f0f1402f05c45bac10814a9e38f81bf

git fsck --no-reflog | awk '/dangling commit/ {print $3}'
git stash apply SHA1_OF_STASH
OR
git branch recovered SHA1_OF_STASH

Commits

Move a commit between repositories

Create patch (mailbox) file (optionally for one specific file):

git checkout sourceBranch
git format-patch -1 SHA1_OF_COMMIT~..SHA1_OF_COMMIT [path/to/file.js]

Apply patch (mailbox) file:

cd toDifferentRepo
git checkout targetBranch
git am pathToPatchFile.patch

Note that the new commit will have a different hash than the original. If you want the hash to remain the same, use git cherry-pick instead.

Squash, re-order, etc

git rebase --interactive HEAD~3

Update last commit message:

git commit --amend -m "New commit message"

Update last committed code (note: not a good idea if others are also working on same repo):

git add .
git commit --amend --no-edit

Can alternatively use this to interactively pick-out files and hunks of lines to be added: git add -p

Show last commit

git show    (shows diff)

Show changes in a specific commit

git show commitID       or       git diff commitID^!

Modify author / date of last commit

Specify a different author for last commit.

git commit -m "msg" --author "John Smith <johnsmith@example.com>"
git commit --amend --reset-author

Change date of last commit.

git commit --amend --date="Wed Feb 16 14:00 2011 +0100" --no-edit
git commit --amend --date=now --no-edit

Tags

Create tag/Set tag

git tag YOUR_TAG_NAME
git tag -f YOUR_TAG_NAME

Pull tags

git fetch origin --tags

Push tag

git tag origin YOUR_TAG_NAME
git push --tags origin

Delete tag

git tag -d YOUR_TAG_NAME
git push --delete origin YOUR_TAG_NAME

Delete ALL tags.

Remote command to delete all tags is first, followed by the command for local tags.

In Linux:

git ls-remote --tags --refs origin | cut -f2 | xargs git push origin --delete
git tag | xargs git tag -d

In Windows PowerShell (remote tags must all exist locally:

git tag | foreach-object -process { git push origin --delete $_ }
git tag | foreach-object -process { git tag -d $_ }  

In Windows Batch:

FOR /f "tokens=*" %a in ('git tag') DO git push origin --delete %a
FOR /f "tokens=*" %a in ('git ls-remote --tags --refs origin') DO git push origin --delete %a

Branches

Checkout a remote branch and create a new local branch with tracking

git checkout -b <newbranch> origin/<branch>
git switch <branch>

or

git checkout --track origin/<branch>

Checkout branch interactively selecting hunks of lines of code

git checkout -p HEAD~

Set tracking for a local branch

git branch -u origin/<branch>

List local and remote branches

git branch -l
git branch -r
git branch -a

Update Branch

https://www.atlassian.com/git/tutorials/merging-vs-rebasing

git pull origin <branch>
git cherry-pick origin/<branch or hash or tag>
git merge origin <branch>

Incorporate upstream changes into branch, moving extra commits to the tip of the branch after synchronising it with the changes from the central repository.

git pull --rebase origin master

Integrating feature/patch/patch from a remote branch - 2 step process:

 git fetch <remote-git-url> <branch or sha>
 git cherry-pick FETCH_HEAD

Rename a branch

git branch -m <NewBranchName>

Compare two branches

git diff branch1..branch2

Delete a local branch

git branch -D <branch>

Delete a remote branch

git push upstream --delete <branch>

Retrieve updates without applying them.

git fetch origin

Push update to remote creating branch if it doesn't already exist.

git push origin HEAD

Push update to a remote different branch

git push origin HEAD:other_branch_name

Set default upstream.

git push -u origin <branch>

Resolving Merge Conflicts

Edit files and then... git add git rebase --continue or get rebase --abort

Stage

git status
git status -uno # Don't show untracked files.
git diff

Show diff with staged files:

git diff --cache [filename]

You can also use git diff to compare the stash with any branch.

git diff stash@{0} master

Remove directory or file from a staged files

git checkout – <file/folder>

Remove directory or file from unstaged files

(just delete the directory or file)

Config

git config --global user.name "Full Name"
git config --global user.email "email@address.tld"
git config --global log.date iso
git config --global color.ui true

Store credentials so you are not prompted again

git config --global credential.helper store

Store credentials for this session only

git config --global credential.helper cache

Set a timeout for credentials

git config --global credential.helper 'cache --timeout=600'

View current configuation

git config --local --list
git config --global --list
git config --system --list

Ignore chmod differences (useful for Windows/Linux)

git config --global core.fileMode false

Log

git log --oneline
git log --author=partofnane
git log --grep=partofmessage
git log --graph --oneline --decorate

Show commits on one line with users and dates

git log --pretty=format:"%h%x09%an%x09%ad%x09%s"

Show last commit

git log --oneline -1  (shows last log)

Show list of ahead commits

git cherry -v
git log origin/master..HEAD
git log --stat origin/master..HEAD
git log master --not --remotes --oneline

Show list of files that changed

git log --name-status

List commits for a specific file

git log --follow -- <filename>
git log --follow -p -- <filename>

Show list of branch heads

git show-ref --heads

List of contributors

git shortlog -s -n

Git Tree

git log --graph --oneline --decorate --all

Show project history and use it to recover almost anything.

git reflog
git reset HEAD@{1}

Reset/Undo

Switch back to previous branch

git checkout --

Restore the file status (undo git add)

git reset --

Revert files from the index (revert files)

git checkout --

Undo "git add" (remove from stage without loosing changes)

git reset HEAD <fileToUnstage>

Undo one or more "git commit" resetting changes

git reset --hard HEAD~
git reset --hard HEAD~5

Undo one or more "git commit" without loosing changes

git reset --soft HEAD~
git reset --soft HEAD~5

Undo one or more "git commit" after git push

Same as undo one or more commits but add a push (note: not a good idea if others are also working on same repo): git push origin HEAD -f

Remove file from repository without deleting it locally.

git rm -r --cached file.name

Undo git reset

git reset 'HEAD@{1}'

Reset to tag instead of branch

git reset --hard YOUR_TAG_NAME

Revert - The Anti-commit

git revert <sha hash>

Submodules

List submodules

git submodules

Add to submodules (.gitmodules)

git submodule add remoteURL destinationFolder

Install submodules

git submodule update --init --recursive .

Get path of all submodules

git config --file .gitmodules --get-regexp path | awk '{ print $2 }'

Update submodules

git submodule update --remote

Remove submodules

git submodule deinit submoduleFolder
git rm submoduleFoder

Other

Get git to prompt for credentials

git config --global credential.github.com.useHttpPath true

Stop tracking a file but keep it (like a "git remove", opposite of git add)

git rm --cached <filename>
git rm -r --cached <filenpath>

Find something in your repo

git grep "regex"

Git Workflows

Git Workflow: Rebase

git checkout master
git pull
git checkout feature-branch
git rebase master
git mergetool
git rebase --continue
git rebase --abort
git push -f

Git Workflow: Create local repository

git init
git remote add <remote> --track origin/<branch>
git add .
git commit -m "Initial commit"
git push origin HEAD

git clone https://github.com/username/repo.git <TargetFolder>

Git Workflow: Make changes to repository

git clone <url>
cd (change directory)
git checkout -b <branch-name>
git status

Make your changes

git status
git diff
git add .
git status
git commit -m "Commit message"
git push

Merge changes from GitHub

git checkout master
git pull
git status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment