Git cheat sheet - the most useful commands

After a little practise, Git can be fully utilised from the command line without any GUI. Adding, committing, pulling, and pushing is part of the daily work; however, there are other commands that are useful but not that frequently used. Here is my collection of those:

# Create and checkout new branch based on the current branch
git checkout -b <newBranch>

# Undo all local pending changes
git reset --hard HEAD

# Erase the last 3 commits
git reset --hard HEAD~3

# Undo a single file change
git checkout -- <fileName>

# Push new branch to server
git push origin <branchName>

# Delete remote branch
git push origin --delete <branchName>

# List all local and remote branches
git branch -a

# Remove remotely deleted branches - will not delete local branches, only copies of remotes
git remote prune origin

# Pull remote master branch and merge it into current branch
git pull origin master

# Undo last commit but keep changes unstaged
git reset HEAD~1

# Rename current branch
git branch -m <newname>

# Save changes temporarily - branch independent
git stash

# List temporary saves
git stash list

# Apply temporarily saved changes
git stash apply

# Delete temporary saves
git stash drop

# Delete untracked files and directories (-n to just test)
git clean -fd

# Resolve conflict by accepting their changes
git checkout --theirs <file>

# Interactive stage / unstage
git add -i

# Compare branch to another branch
git diff <otherBranch>

#display all changes with additions/deletions between two branches
git diff --stat master..<otherBranch>

#display the active branches
git branch -va --sort=committerdate

#display the active branches - fancy colours and author info
git branch -r --sort=committerdate --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'

# Working with github forks
# If you want to keep working on your work, you need to hard-reset it to the owner's changes

git remote add upstream https://github.com/owner/repo
git fetch upstream
git checkout master
git stash # In case you have local changes, you *must* stash them
git reset --hard upstream/master  
git push origin master --force
git stash apply # If you had local changes before update

Comments

Popular posts from this blog

MurMurHash3, an ultra fast hash algorithm for C# / .NET

ESP32 - send a push notification from the Arduino ESP32 device to your phone

Octoprint as a systemd service - running it with high priority