Most common Git Commands

Most common Git Commands

This article contains few common git commands that is used almost every time we interact with git.
git config
To configure common configuration values like user email id, name, console colors etc. For instance to set git user.name to Foo use the following command.
 git config --global user.name "Foo"
Initialize a repo
Create an empty git repo or reinitialize an existing one
git init
Clone a repo
Clone the foo repo into a new directory called foo on local workstation.
git clone https://github.com//foo.git foo
Create new Branch
Now that we have a repo, we might want to create a branch and work on it
git branch LOCAL_BRANCHNAME
Checkout a different branch
Now that we have created our branch, lets say we want to checkout a different remote branch.
git checkout -b LOCAL_BRANCHNAME origin/REMOTE_BRANCHNAME
Switch branch
Switch between multiple branch
git switch -c NEW_BRANCHNAME
Unstaging Changes / Restoring Files
Maybe you accidentally staged some files that you don't want to commit.
//restore a single file
git restore foo.js
//restore all the files
git restore .
Commits
To commit the staged files execute the following commands.
 git commit -m " updated foo.js with mew controller"
Undoing Soft Commits
The next one will completely delete the commit and throw away any changes. Be absolutely sure this is what you want.
git reset --hard HEAD~1
Squashing Commits
If we want to combine multiple commits to a single commit so that it is easy to review. Following command will combine 5 different commits to a single commit. With a single commit message
git rebase -i HEAD~5
Pushing Commits
Push the commits from the branch to remote branch.
git push origin BRANCH_NAME
Undo Last Push
If we want to undo changes that were pushed using last commit, we can use the following command to undo it.
git reset --hard HEAD~1 && git push -f origin master
Fetch
Download objects and refs from another repository.
git fetch
Merging
Suppose we want to get the latest from the remote branch named "REMOTE_BRANCH" to local working branch. Execute the following command.
git fetch origin
git merge origin/REMOTE_BRANCH
Pulling
Git Pull is the way to get the latest changes from remote branch and apply on local branch. It might cause merge issues if the local branch is not clean.
git pull origin/REMOTE_BRANCH
Rebasing
Git rebasing is the way to
git fetch origin
git rebase origin/REMOTE_BRANCH
Stashing
Stash the changes in the working directory away, so that later they can be taken back. Use git stash to shelve local changes so that can be applied later with with stash apply. Use stash list to see contents in the shelve.
git stash
git stash pop
git stash apply
git stash list

Summary

Git is the most commonly used version control system. Above commands are some very common commands for reference.

No comments :

Post a Comment

Please leave your message queries or suggetions.

Note: Only a member of this blog may post a comment.