Git is a free and open source distributed Version Control System (VCS) designed to handle everything from small to very large projects with speed and efficiency. It is designed to track changes to a project (code) in software development. It is intended to enforce coordination, collaboration, speed, and efficiency among developers.
Version control, also known as source control, is the process of tracking and managing changes to files over time. VCS are software tools designed to help teams work in parallel and manage source code.
In this article I am going to explain how to work with Git and list out frequently used Git commands. Before moving to the git commands, let us first understand the basic git workflow:
Step 1 − You clone or download a copy of project source code from remote git repository to your local machine’s workspace.
Step 2 − You modify, add or delete files in your downloaded copy of project.
Step 3 − You add these files to the git staging area.
Step 4 − You perform commit operation that moves the files from the staging area.
Step 5 − You perform push operation, it stores the changes permanently to the remote Git repository.
1. Configure Author Details And Other Settings:
It is imperative to configure author details in git before performing any git commit operation. git config
command is used to set the author name and email address respectively. This information is used by Git for each commit. Git stores all global configurations in .gitconfig file, which is located in your home directory . The usage is given below, we need to execute following two commands to set name and email address.
git config –global user.name "<your-name>"
git config –global user.email "<your-email-address>"
# Example:
git config –global user.name "James Bond"
git config –global user.email "[email protected]"
Configuration to avoid merge commits while pulling:
When we pull the latest changes from a remote repository, and if these changes are divergent, then by default Git creates merge commits. We can avoid this by using the following settings.
git config --global branch.autosetuprebase always
To view all the settings, you can use git config --list
command.
git config --list
# Output example:
user.name=James Bond
[email protected]
branch.autosetuprebase=always
...
2. Cloning Code Repository:
Cloning code repository basically means downloading a copy of code repository or project source code from remote Git repository to our local machine. git clone
command used to clone remote repository.
git clone <url>
# Cloning Specific Branch:
git clone -b <branch-name> <url>
OR
git clone --branch <branch-name> <url>
# Example:
git clone https://github.com/projects/project-1.github.io.git
git clone -b new-idea https://github.com/projects/project-1.github.io.git
3. Checking Local Code Changes:
Once project source code is cloned in our local machine, we will start working on the project and do some changes to existing source code files or create new files as required to complete the given task or requirement. git status
command is used to check the changes that has been made to project source code. This command will list all the modified, newly added and deleted files.
git status
This command also shows the current branch name that we are working on.
4. Committing And Pushing Code Changes:
As soon as the task is completed and tested locally, we need to make the changes available to every one who is working on the same project. To do so, we need to add modified or new file(s) to git stage (git add
), commit the changes (git commit
) and then push to changes (git push
) to remote repository.
4.1) Adding Files to Git Stage:
Adding file(s) to Git stage or Git staging area means saving a copy of the current state of the project. This tells Git that you want to add the files to the next commit you do.
# Adding single file to stage
git add <file-name>
Example:
git add dashboard.html
# Adding multiple file to stage, as many you want
git add <file-1> <file-2> <file-3>
Example:
git add dashboard.html main.js style.css
# Adding all files to stage
git add *
OR
git add -A
OR
git add .
OR
# Adding all files by extension
git add *.<extension>
# Example:
git add *.js
4.2) Committing Changes:
The commit command is used to save changes to a local repository after staging in Git. We commit our changes with git commit
command as shown below. It is good practice to add meaningful message to each commit to identify your changes. We should describe what changes we are going to commit.
git commit -m "Commit message that describes what this change does"
//Example:
git commit -m "TASK 123: Add trend pie chart in dashboard"
Always follow the commit message convention defined by your team or follow the best practices.
We can also add modified files to the staging area and commit them at the same time. Git provides the following super command:
git commit -a -m "TASK 123: Add trend pie chart in dashboard"
4.3) Pushing Changes to Remote Repository:
The git push
command is used to upload local repository content to a remote repository. Pushing is how you transfer commits from your local repository to a remote repository.
git push
5. Deleting or Reverting Local Changes:
If you have done some changes to source code and want to revert it back, then you can use git reset
command to do so.
git reset --hard
This will restore everything to recent. It will remove the available changes from the staging area. It will also remove newly added files as well.
If you want to keep the changes, but remove from staging area, use --soft
option.
git reset --soft
For more details on git reset read Git Reset Vs Git Revert
6. Pulling Changes:
Pulling is basically opposite to pushing. When we do a ,code pull, we get all the changes that has been made by other developers in the project.
git pull
Note: It is good practice to pull code before you commit any changes. Otherwise most of the time you will face git error.
7. Create, List, Switch, Delete, Merge Branch:
The git checkout
command is used to switch from one branch to another in a repository and to create a new branch as well.
# Switch to another branch
git checkout <branch-name>
# Create and switch to new branch
git checkout -b <new-branch-name>
# Example: Switched to another branch 'release-2'
git checkout <release-2>
# Example: Create and switch to new branch 'release-3'
git checkout -b release-3
git branch
command is used to list all the branches in the working repository. It is also used to create new branch, delete existing branch from repository and merge one branch with another.
# List all branches
git branch
# Creates a new branch
git branch <new-branch-name>
# Delete branch
git branch -d <branch-name>
# Merge Branch
git merge <target-branch-name>
To merge branches, you should first checkout the source branch (where you want me merge) and pull so that you have all latest code in the same. Then run the merge command. Don’t forget to create a git tag before you merge.
8. Stashing and Unstashing Changes:
git stash
command locally stores all the most recent changes (backup all changes made) in a workspace and resets the state of the workspace to the prior commit state. A user can retrieve all files put into the stash with the git stash pop
and git stash apply
commands.
# Backup all your local changes in the workspace
git stash
# Restore stashed changes or unstash
git stash apply
OR
git stash pop
# lists all stashed changesets
git stash list
# Discard the most recently stashed changeset
git stash drop
Tip: Stashing can be used to prevent merge conflict if applied wisely. Let’s consider a very common scenario – You want to pull latest code, but you have some uncommitted changes locally. Git is not allowing you to pull code unless you commit your changes. What should you do? Yes, use Git stash feature. Stash the changes first, then do a git pull and finally do unstash to restore and merge the stashed code. If you face any merge conflict after unstashing, resolve it manually and then commit and push your changes.
# Backup your changes
git stash
# Pull latest code
git pull
# Restore backed up changes
git unstash apply
9. Fetching Changes:
You can use git fetch
to know the changes done in the remote repo/branch since your last pull. This is useful to allow for checking before doing an actual pull, which could change files in your current branch and working copy (and potentially lose your changes, etc.).
How git fetch is different from git pull?
git fetch
is the command that tells your local git to retrieve the latest meta-data info from the original (yet doesn’t do any file transferring. It’s more like just checking to see if there are any changes available). git pull
on the other hand does that AND brings (copy) those changes from the remote repository.
10. Remove File(s) From Staging Area:
If you have accidentally added some file(s) to git stage and do not want it to commit, you can use git restore
command to remove it from staging area.
# Remove a specific file from the staging area
git restore --staged <file-name>
# Remove all the files that are currently staged
git restore --staged .
# Alternatively, you can use git reset command
git reset <file-name>
11. Revert Committed Changes :
Many times for different reasons, we might need to revert committed changes. Let’s say you pushed some new changes (feature or bug fix) and it did not work as expected or it is breaking some other functionality. In such cases, we need to revert the changes immediately. There are two ways to do it –
a) One way is manually revert the changes and then commit and push the code. If the changes are small like just one file was modified or added just few lines of code then this is feasible. But if the changes are huge, manually reverting will be hectic job.
b) Another way is using git revert
command. This command is life saver! To revert a particular commit, following command can be used-
git revert <commit-hash>
You need to pass the commit hash of the commit you want to revert. It can be picked from git log. To view git log i.e. git commit history, just run git log
command-
git log --oneline
For more details on git revert read Git Reset Vs Git Revert
Cheat Sheet
# Git Configuration
#-------------------
git config –global user.name "James Bond"
git config –global user.email "[email protected]"
git config --global color.ui true
git config --list
# Starting a Repository
#-------------------
git init
git status
# Stagging Files
#-------------------
git add dashboard.html
git add dashboard.html main.js style.css
git add .
git add *
git add --all
git add *.js
// Remove staged file
git rm --cached my-file.ts
git reset another-file.js
// Revert local changes
git reset --hard
git reset --soft
# Committing
#-------------------
git commit -m "TASK 123: Add trend pie chart in dashboard"
// Add modified file(s) to stage and commit at the same time
git commit -a -m "TASK 123: Add trend pie chart in dashboard"
# Pulling & Pushing From/To Remote Repository
#-------------------
// Create local repository by cloning remote repository
git clone [email protected]:YourUsername/your-app.git
// Add remote origin to already started/created local git repository
git remote add origin https://github.com/YourUsername/some-small-app.git
// View remote origin (remote repository) url
git remote -v
git push
git pull
# Reverting Commit
#-------------------
git revert <commit-hash>
# Resetting (Deleting) Commits
//Should not be done in public repository
// Delete last commit
git reset --hard Head~1
// Reset to a particular commit
git reset --hard <commit-hash>
git reset --soft <commit-hash>
# Branching
#-------------------
git branch
git branch <branch-name>
git checkout <branch-name>
// Create branch and checkout at the same time
git checkout -b <branch-name>
git fetch
git merge <target-branch-name>
git branch -d <branch-name>
# Checking Git Commit history OR Log
#-------------------
git log
git log --stat
git log --oneline
git log --graph
git log --graph --oneline
git log --patch or git log -p
To learn more on frequently used git commands read Frequently Used Git Commands