Skip to content

Git useful commands

In this post I will share a collection of Git useful commands that I’m certain we will need during our daily work as a developer. I will keep updating this list as I come across other operations.

Please use some of these commands with caution, as they may lead you to data loss if don’t know exactly what you’re doing.

Repositories

Init a repo

git init

Clone a repo

git clone <repo_url>

Pull

Pull the latest changes

git pull

Pull unrelated changes

You might need this when you just created a new repo on the remote server and then initialised it with a file, but you also initialised a git repo locally. That means that the master branch on the remote repo started differently from the master branch locally, hence, they are unrelated.

git pull --allow-unrelated-histories

Push

Push into the remote

git push

Push into a specific remote

git push -u <remote_name>

Branches

Checkout a branch

git checkout <branch>

Create and checkout a branch

git checkout -b <branch>

Checkout a specific tag

git checkout tags/<tag_name>

Show local branches

git branch

Show remote branches

git branch -r

Show all branches

git branch -a

Show remote branches including any not tracked

git remote show origin

Merge two branches

The following merges the changes from master into a custom my-feature-branch:

git checkout my-feature-branch
git merge master

Stash

A stash is a separate working directory used to keep the changes you’d like to get rid for now. Useful for when you decide not to include a specific change as part of the commit, but need it later for another set of changes.

Stash all local changes

git stash

View the contents of the most recent stash

git stash show -p

View the contents of an arbitrary stash

git stash show -p <stash_reference>

Remove all stashes from the repo

git stash clear .

Undoing things

Undo all local commits

git reset HEAD~

Undo the last commit on the remote repo

For example, the commit id aed94874 will be removed from the branch master

git push origin +aed94874^:master

Undo all changes including new files

You will lose your changes.

git reset --hard
git clean -fd

Combos

I personally always create aliases for the following set of commands in my operational system.

Pull changes and tags, then remove old branches

git checkout master &&
git pull &&
git fetch --tags &&
git remote prune origin &&
git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk '{print $1}' | xargs git branch -d

Set a different committer for the project

git config user.name "bgasparotto"
git config user.email "bruno.m.gasparotto@gmail.com"
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *