Git Commands — Quick Guide
This story explains and list important Git commands for reference
What is Git ?
Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.
Git is Decentralized/Distributed version control system. Most operations in Git are local. Only few commands need n/w access. Git is Super Fast as most operations are local Free/open source.
What is a Repository?
It is described as Collection of Files Managed by Git and History of all them.
Commits and Files:
All the files managed by git are called Snapshots which are called commits One or More File Changes.
Git States:
There are 3 Git states:
(1) Working Directory: Contains all files and folders related to our project
(2)Staging Area: Staging area is used to prepare for the next commit. Modified or added Files are moved from working directory state to the Git staging area and finally committed to the Git Repository.
(3)Repository(.git folder):Contains all committed and Saved changes of Git Repository in the folder called .git
(4) Remote: The above 3 states are related to local git repository. Remote is the repository that is maintained remotely . All files and folders in local are pushed to remote repository so that they can be accessed by anyone who needs to access the code.
Git Commands:
(1)Git Command for Setting up username in Git:
Step 1: Open Terminal
Step 2: Set a Git username and user email:
git config — global user.name “your Name”
git config — global user.email “ your@email.com”
Set user name locally:
git config user.name “ABCCCC”
To retrieve that
git config user.name
(2) Git command to Create a repository and initialize with Git:
git init demo
Note: Where “demo” is repository/directory name.
(3)Git command to view all files and projects of Git Repository:
ls -al
(4)Git command to display the status of the current Directory:
git status
(5)Command to List all the files and directories in the current directory:
ls
(6)Git Command To Add a File to Git Directory:
git add MyFile.txt
Here “MyFile.txt” is the file to be added to the Git directory.
When the above command is executed ,the file is moved to staging state and is about to be committed. “git add “ command will add all files in directory to the staging area.
When Multiple files are added . To add all files at a time, use the below version of add command. git add followed by dot
git add .
(7)Git Command to commit all changes to local repository:
Version 1 :git commit -m “First Commit from Demo”
Where “First Commit from Demo” is the message to be passed during commit.
Version 2 (Express commit) : git commit -am “Commits all modified files on one go”
When multiple modified files to be committed at a time, instead of executing add command ,followed by commit command, we can directly use the above command which is called “Express commit”.
(8) Command to return to command prompt:
:qa!
The above command to be used to exit from Commit option and return to current command prompt .Type :qa! and press to abandon all changes and exit Vim.
(9)Command to get Home Directory:
pwd
Use pwd to know PresentWorkingDirectory.
(10)Git Command to view all commit logs :
Version 1: git log
Version 2: git log --pretty=oneline
Version 3 : git log --oneline --graph --decorate
(11)Git Command to show the last commit and a diff containing all the changes:
git show
Note: Press q to get out of the show command
(12)Command to remove a file from the directory:
rm newFile
Removes a file with name “newFile” in the directory.
(13)Git Command to reset changes in a file:
git reset HEAD MyFile.txt
where MyFile.txt is the file to be reset
(14)Git command To display all commits in a single line:
git log --oneline --graph --decorate --all
Sample Output for the above command:
- 96daa21 (HEAD -> master) Commit
- 3316a78 Express Commit
- 4d0d62d 3rd Commit
- 1a72bae 2nd Commit from Demo
- ec183f8 First Commit from Demo
- 9bf99e6 First Commit from Demo
(15)To Create our own Git command:
git — global alias.hist “log -- oneline -- graph --decorate --all”
where “hist” is the alias command for git log
(16)Command to Rename a File:
mv is the command to which we need to input source and destination files.
git mv NewTestFile.txt NewTestDemoFile.txt .
(17)To Remove a file
git rm NewTestDemoFile.txt
(18)Git Command to See differences b/w commits
git diff ec183f8 HEAD
Note: “ec183f8” is commit Id which is compared with “HEAD”
(19)Command to See Differences between Branches
git diff master updates
Note: Where master and updates are 2 different branches.
(20)What is HEAD?
HEAD is generally last commit to the current branch.
(21)Git Command to fetch the name of the current branch we are in
git branch
(22)To Create a new branch and switch to it:
git checkout -b branchname
Ex: git checkout -b feature-new-branch
(23) To checkout to a new branch
git checkout branchname
(24)Git Command to Merge branches:
git merge updates
Example: Currently we are in master branch and want to merge changes made in “updates” branch. Use the above merge command.
(25)Git command to delete a branch:
Version 1: git branch -d updates (Local branch will be deleted)
Note: Where “updates” name of the branch to be deleted
Version 2: git push origin :feature_remote_branch
Once a branch is removed from local and it still exists in Remote. We can remove the branch at remote using above command (Version 2)
(26)Git command to display list of all branches
git branch -a
(27) Commands related to Tags: Tags are just labels that you can put on any arbitrary commit point.
There are 2 types of Tags:
(1) Light Weight Tag: No Associated information about the Tag be provided for light weight Tag.
git tag myTag
(2) Annotated Tag: Provides information about a Tag.
git tag -a v1.0 -m “Release 1.0”
To Display information about Tag:
git show v1.0
To Display list of all Tags:
git tag --list
To Delete a Tag (Example : to delete mytag):
git tag -d mytag.
To push a Tag to Remote:
git push origin stable (where origin is remote repository and stable is Tag created locally )
To push all Tags:
git push --tags
Sample Examples of Tags:
Ex:1
git tag unstable develop
This tag “unstable” creates a new tag in develop branch for last commit happened in develop branch
Ex :2
git tag stable master (Creates a stable tag on the master branch)
Ex:3 Annotated Tag
git tag -a v0.1-alpha -m “Release Alpha “ a434b4d
Where a434b4d is commit id
Ex : 4 - Displays information about Tag
git show v0.1-alpha
EX: 5 Commands to push Tags
Creating Tags:
1.git tag -a v0.2-alpha -m “Release Alpha “ 67cc135
2.git tag -a v0.3-alpha -m “Release Alpha3 “ 8bf4de7
Pushing Tags:
3. git push origin stable (Pushes stable tag to origin which is remote)
4.git push --tags (To push all Tags)
Examples to Delete a Tag:
To Delete a Tag from local that is already deleted in Github.
Suppose “v0.1-alpha” Tag is already deleted in Github
Calling git Tag command displays all Tags available in local
git Tag
Displays the below available local tags when called git Tag:
stable
unstable
v0.1-alpha
v0.2-alpha
v0.3-alpha
v1.0
Call the below fetch command followed by Tag delete command:
git fetch -p
git tag -d v0.1-alpha
To Command delete a Tag in Local and push to Github:
Delete tag from Local:
git tag -d v0.2-alpha
git push origin :v0.2-alpha
Updating Tags and Pushing in Github:
Steps:
1.To update existing tag to latest commit Id
git tag -f unstable 97cb3ef
(Note: where “unstable” is tag name and “97cb3ef” is commitId)
2.To push a updated Tag Forcibly to Github:
git push — force origin unstable.
Difference b/w Releases and Tags:
There is no much distinction b/w Releases and Tags.
In Releases Tab : All Tags are displayed
In Tags Tab : All Tags are displayed along with Release notes for each Tag Creating a Release : In the Tags Tag -> Select any Tag -> Click on 3dots and Create a release by providing release. We can edit/delete a release also once created.
(28) Stashing:
Git Stash is used when we don’t want to commit change right away and want to commit later and save that changes for later .
git stash
output:Saved working directory and index state WIP on master: e953595
To display list of all stash:
git stash list
Apply stash:To apply stash and drop the stash after changes are applied use the below command.
git stash pop
To add untracked files to Stash:
git stash -u
Note: This situation may occur when soft reset is done and corresponding file is untracked.
To Save Stash:
git stash save -u This is saved Stash
(29) Rollback:
- Soft Reset: git reset 97cb3ef --soft
Soft reset just changes commit to where Head is pointing . Soft reset is less destructive)
2.Hard Reset :
git reset --hard 97cb3ef
Hard reset is most destructive . It wipes out all changes and points to HEAD.
Soft Reset Example:
Example:
Scenario 1:
Create a new File and modify existing file.
Then run git add . command
Now check status using git status -s
To reset the changes use below command
git reset head
output :Unstaged changes after reset:
M NewInfo.txt
Scenario 2:
To reset only specific file
git reset NewInfo2.txtScenario 3: To reset to some commit id
get reset cea07fg
(30) git reflog
git reflog : This command Shows all the different actions taken in the repository where as Where as git log shows only commit info.
(31)git remote -v
Git responds if there is a remote Repository linked to local Repository
Example : To add remote Repository
git remote add origin https://github.com/abc34455/GitPractice2020.git
(32) Git Pull:
Pull command will merge the changes from remote to local.
To pull from Origin to the local branch use Git pull command as below:
Version 1:
git pull origin master (Where origin is Remote Repository and master is local repository)
Version 2:
git pull origin master — allow-unrelated-histories.
Version 3:
To rebase branch to the remote branch during pull , use the below command:
git pull — rebase
(33) Fetch
Fetch command will just get the changes from remote to local , but will not merge.To merge we need to use Pull command.
Version 1: git fetch
Version 2: git fetch-p ( Where -p is the prune option)
Version 3: git fetch origin --prune (Another version of Prune)
The above command to be used when a feature branch is deleted at Remote and still exists locally.The local branch to be deleted using branch delete command.But still we see stale reference of this branch locally.In order to remove that stale reference of branch locally we need to use git fetch with Prune option which looks for any dead branches and remove those references.
(34) Push:
Git Push command is used to push changes from local master branch to the Remote branch
Version 1: git push origin master
Version 2: git push -u origin master-- tags
The above pushes the tags created from local master branch to origin
Version 3: To push Existing Repository from Command line
git remote add origin https://github.com/abc34455/GitPractice2020.git
git push -u origin master
(35) Clone: git clone command is used to clone project from remote.
Version 1 :git clone https://github.com/github3455/GitPractice.git
Version 2 : git clone https://github.com/github3455/GitPractice.git MyFolder
Note: By default Project/Files from Remote repository are cloned with default folder name as is in Remote Repository. To Explicitly specify local folder name , the above command to be executed.
Cloning Specific branch from Git:
git clone -b <branchname> <remote_repo link>
git clone -b myBranch https://github.com/github3455/GitPractice.git
(36)Setting Remote Repository URL when Repository name is changed:
When a remote repository name is changed (Ex: ABC_Remote to ABC_REMOTE_REPOSIT) then in order to have local Repository point to the renamed repository use the below command:
git remote set-url origin https://github.com/github3455/GitPractice.git
(37)To get additional info about remote Repository:
git remote show origin
(38)To get information about specific commit :
use git show followed by commit message
Ex: git show 3791f7c26f9d7ae8faff291999fe9fee1a62d237
(39)Remove a File:Navigate to the path where the file exists and use the below command
git rm GitInfo.kt
(40)To see the list of all files in a folder/directory
ls -l
(41)Merge a branch to master branch :If you want to merge another branch to master use below command . First switch to master branch and then execute below command
git merge feature_local_branch
(42)Git Rebase:
In Git, the rebase command integrates changes from one branch into another. It is an alternative to the better known “merge” command. Most visibly, rebase differs from merge by rewriting the commit history in order to produce a straight, linear succession of commits.
Steps:
(1) Make a change to Readme file in master branch from Remote and commit. (2) Make a change to “MainActivity” file in master branch from local and commit.
(3) call git fetch command Displays the below message: Your branch and ‘origin/master’ have diverged, and have 1 and 1 different commits each, respectively. (use “git pull” to merge the remote branch into yours)
(4) calling git pull is okay , but if we want whatever we are currently working on stays ahead of whatever currently on Github (remote). To do that use rebase with pull as below.
(5) git pull --rebase
(6) Executing above command gives below result:
GitPractice $ git pull-- rebase
First, rewinding head to replay your work on top of it… Applying: updated MainActivity locally before Rebase
(7) Type command git log to see the rebase Changes (git log --oneline --graph --decorate --all
)
The rebase brought in changes from Github and placed before them before our changes we had locally(8) Observe that the changes from Github are already updated to your local Readme file.
(9) Now push the changes we made on another file in our local Repo.
(43) amend commit:
amend command is a convenient way to modify the most recent commit.
Rewriting history of the commit by Changing the Last Commit.
Example:
Steps for Amend Commit:
Step 1 : First do a normal commit
git commit -am "Fresh Commit on Ammend"
Step 2: git log --oneline (To see the log history of Commits)
a119e82 (HEAD -> develop) Fresh Commit on Ammend
Step 3: Execute amend commit command as below with new commit message
git commit --amend -m "Modified Fresh Commit on Amend"
Step 4 : git log --oneline
Observe new commit id is displayed with modified message . Previous commit message is not displayed in History
f782108 (HEAD -> develop) Modified Fresh Commit on Amend
Example 2:
Suppose we add a file and we want this file to be part of the last commit instead of new commit.
Then also we can go for amend commit.
Step 1: Just capture previous/recent commit id for reference using below command
git log --oneline
78eb2d8 (HEAD -> develop, origin/develop, origin/HEAD) Updated with Amend commit info
Step 2 : Create a new file using the below command:
touch info.txt
Step 3 : Use amend command as below
git commit --amend -m "added info.tx file as part of ammend command"
Step 4: execute below command and observe the commit id and observe the previous commit message is not seen as part of history
git log --oneline
11bd828 (HEAD -> develop) added info.tx file as part of ammend command
(44) Command for Time Intervals an GarbageCollection:
Time Intervals:
git reflog HEAD@{1.days.ago}
git reflog HEAD@{25-05-2020}
To See Differences:
git diff HEAD@{4} HEAD@{5}
git diff 8c4bcdf 3d4e111 (Where 8c4bcdf and 3d4e111 are commit ids)git
Git reflog to clean up unreachable commits:
git reflog expire --expire-unreachable=now --all
Followed by
git gc --prune=now
(45) To Clean Repository:
git clean -d -x -f
Note: Not preferable .
(46) To revert a commit:
git revert 540b440 (Where “540b440” is commit id)
(47) Creating patches :
git format-patch -1 501c0e4d6b9ca8f52b5775c2afddd4bb9dab7771 -o patches
Where 501c0e4d6b9ca8f52b5775c2afddd4bb9dab7771 is commit id
patches is directory in which this patch is stored.
Now Checkout to another branch where we need to apply this patch.
git am patches/0001-Create-patch.patch
(48) Rename a branch:
Steps:
(1) Select the branch to be renamed under “Local Branches” in Android studio. Click on the arrow to find 2 options : one is “rename “ and other is “push”
(2) Rename the branch with new name by selecting “rename “ option.
(3) Now select the original branch under “Remote Branches” in Android studio. Click on arrow on the right hand side and select delete option to delete the remote branch.
(4) Now click on right arrow under newly renamed branch located under “Local Branches” in Android studio and select “push” option to push branch to Gitlab.
49: Steps to create/push
Git global setup
git config --global user.name "abc"
git config --global user.email "abc@def.com"
Create a new repository
git clone https://github.com/github3455/GitPractice.gitcd foldername
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master
Push an existing folder
cd existing_folder
git init
git remote add origin https://github.com/github3455/GitPractice.git
git add .
git commit -m "Initial commit"
git push -u origin master
Push an existing Git repository
cd existing_repo
git remote rename origin old-origin
git remote add origin https://github.com/github3455/GitPractice.git
git push -u origin --all
git push -u origin --tags
Push new project to Remote:
git remote add origin https://gitlab.abc.com/myapp.git
git remote -v
git add .
git commit -m “First Commit”
get fetch
git pull remote master — rebase ( Example: git pull origin master — rebase)
git push — set-upstream remote master (Example : git push origin master)
Stash:
git stash
git stash branch temp-branch
git add .
git commit
git checkout destination-branch
git merge temp-branch
git branch -D temp-branch