Using git

Repositories

Get the repository status

git status

Initialize a repository

git init

Initialize a bare repository

A bare repository contains only a .git directory. Bare repositories can be used on git servers and/or with git hooks.

git init --bare

Clone a remote repository

Clone branch targetBranch of the remoteRepository into targetDirectory:

git clone -b targetBranch remoteRepositoryUrl targetDirectory

Committing work

Stage all modified files for commit

git add .

Commit with staging files and adding a commit message

git commit -am "Commit message"

Save non-commited work to make pull

If you need to make a pull, but you have made some modifications you cannot commit for now, you can use a combination of git stash - git stash pop commands.

The process can be the following:

  • save non-commited work:
git stash
  • temporarily checkout another branch

  • checkout your working branch

  • apply your saved changes:

git stash pop

Discard all changes till the most recent commit

git reset --hard

Modify the most recent commit

If you need to modify the most recent commit without changing the commit message:

git commit --amend --no-edit

Branches

Get all branches

git branch -a

Checkout a targetBranch

git checkout targetBranch

Create a newBranch from the current branch

git checkout -b newBranch

Remotes

Get all remotes

git remote -v

Add a remote

git remote add <remoteName> <remoteRepositoryUrl>

Modify remote repository url

Supposing we need to modify the remote (which is called origin) url from url1 to url2:

git remote set-url origin url2

Pull workingBranch from the sourceRemote

In order to have the local workingBranch synchronized with the one from the sourceRemote.

git pull sourceRemote workingBranch

Avoid redundant MERGE commit on pulling

Pull workingBranch from the sourceRemote with rebase:

git pull --rebase sourceRemote workingBranch

Push workingBranch to the targetRemote

git push targetRemote workingBranch

Push workingBranch to the targetRemote with setting an upstream

Usually an upstream is set on the first push of the branch to remote.

git push -u targetRemote workingBranch

Force push workingBranch to the targetRemote

Sometimes necessary after doing an interactive rebase, as remote and local versions of workingBranch are different and the local version cannot be pushed to targetRemote:

git push --force targetRemote workingBranch

Or a safer version:

git push --force-with-lease targetRemote workingBranch