Common git commands

Simple guide to get started with Git.

Configure author and email address to be used with your commits

git config --global "John Doe"
git config --global [email protected]

Create a new local repository
Create a new directory, go into it and run

git init

Connect to a remote repository

git remote add origin <server>

Checkout a repository
Create a working copy of a local repository:

git clone /path/to/repository

For a remote server, use:

git clone username@host:/path/to/repository

Get Status:
List the files you modified and need to be added

git status

Add files
Add one or more files to staging (index):

git add <filename>

git add *

Commit changes to HEAD (but not yet to the remote repository):

git commit -m "Commit message"

Push Changes to remote repository
Send changes to remote repository master branch. Replace master with any branch you want.

git push origin master

Make sure to create your own feature branch from your base branch so that your base branch is always clean. And don’t forget to rebase it with your base branch regularly 🙂

Create a new branch and switch to it

git checkout -b <branchname>

Switch from one branch to another

git checkout <branchname>

List all the branches in your repo, and also tell you what branch you’re currently in

git branch

Push the branch to your remote repository
Your branch is not available to others unless you push the branch to your remote repository.

git push origin <branchname>

Delete the feature branch

git branch -d <branchname> //Delete the branch if it has already been fully merged in its upstream branch
git branch -D <branchname> //Delete branch irrespective of its merged status.
git push origin :<branchname> //Delete a branch on your remote repository

Fetch latest commit from remote server to your local directory

git pull

Merge another branch into your active branch

git merge <branchname>

// Merging might be painful sometimes. Though Git tries to auto-merge the changes, there is always a chance of getting conflicts while merging. In this case we manually resolve conflicts.

git diff //View all the merge conflicts
git diff --base <filename> //View the conflicts against the base file
git diff <sourcebranch> <targetbranch> //Preview changes, before merging

//After conflicts are resolved we need to mark them as merged by
git add <filename>

Create tags for software releases.

git tag 1.0.0 <commitID> //<commitID> is the leading characters of the changeset ID, up to 10, but must be unique. Get the ID using "git log"

git push origin <tag_name> //Push tag_name to remote repository
git push --tags origin //Push all tags to remote repository

Drop all your local changes

git fetch origin

git reset --hard origin/master

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.