How to use GIT commands for clone, push, add, commit, checkout etc.?

Total
0
Shares

Git’s job is to create and save snapshots of your project and compare them with later snapshots.

This article describes commands for creating and committing snapshots of your project.

Git commonly uses the following six commands: git clonegit pushgit addgit commitgit checkoutgit pull which we will learn in detail.

A simple operation step:

$ git init    
$ git add .     
$ git commit  
  • git init – Initialize the repository.
  • git add . – Add files to the staging area.
  • git commit – Add the staging area content to the repository.

Commands for creating repository

git init

The git init command is used to create a new Git repository in a directory.

Execute git init in the directory to create a Git repository.

For example, we create a project named techinplanet in the current directory:

~$ mkdir techinplanet
~$ cd techinplanet/
~/techinplanet$ git init
Initialized empty Git repository in /Users/tech/techinplanet/.git/

Now you can see that the .git subdirectory is generated in your project. This is your Git repository, and all the snapshot data about your project is stored here.

.git is hidden by default and can be viewed with the ls -a command:

ls -a
.    ..    .git

git clone

git clone copies a Git repository locally so that you can view the project or make changes.

The format of the clone command is as follows:

git clone [ url ]

[url] is the url of repository, you want to copy.

For example, we copy the project on Github:

$ git clone https://github.com/akamittal/akashmittal-articles.git
Cloning into 'akashmittal-articles'...
remote: Enumerating objects: 12, done.
remote: Total 12 (delta 0), reused 0 (delta 0), pack-reused 12
Unpacking objects: 100% (12/12), done.

After the copy is completed, a akashmittal-articles directory will be created in the current directory.

By default, Git will create your local project directory with the name of the project pointed to by the URL you provide. Usually this is the project name after the last / of the URL. If you want a different name, you can append the custom name to this command.

For example, the following command will copy the akashmittal-articles repository in name articles

$ git clone https://github.com/akamittal/akashmittal-articles.git articles
Cloning into 'articles'...
remote: Enumerating objects: 12, done.
remote: Total 12 (delta 0), reused 0 (delta 0), pack-reused 12
Unpacking objects: 100% (12/12), done.

Commands for Submit and Modify

Git’s job is to create and save snapshots of your project and compare them with later snapshots.

The following commands are for creating and committing snapshots of your project:

git add

The git add command adds the file to the staging area.

Add one or more files to the staging area:

git add [file1] [file2] ...

Add the specified directory to the staging area, including subdirectories:

git add [dir]

Add all files in the current directory to the staging area:

git add .

In the following example we add two files:

$ touch README                 # create file 
$ touch hello.php              # create file
$ ls
README        hello.php
$ git status -s
?? README
?? hello.php
$ 

The git status command is used to view the current status of the project.

Next we execute the git add command to add the file:

$ git add README hello.php 

Now when we execute git status again, we can see that these two files have been added.

$ git status -s
A  README
A  hello.php
$

In a new project, it is common to add all files, we can use the git add . command to add all files of the current project.

Now we modify the README file:

$ vim README

Add the following to the README: 

# TechInPlanet 

, then save and exit.

Execute git status again:

$ git status -s
AM README
A  hello.php

The AM status means that the file has changed since we added it to the cache. After the change, we execute the git add . command to add it to the cache:

$ git add .
$ git status -s
A  README
A  hello.php

After the file is modified, we generally need to perform the git add operation to save the historical version.

git status

The git status command is used to see if a file has been modified since your last commit.

$ git status
On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   README
    new file:   hello.php

Usually we use the -s parameter to get a short output:

$ git status -s
AM README
A  hello.php

The AM status means that the file has changed since we added it to the cache.

git diff

The git diff command compares the differences between files, that is, compares the differences between files in the staging area and the working area.

The git diff command shows the difference between files that have been written to the staging area and files that have been modified but not yet written to the staging area.

There are two main use cases for git diff.

  • Changes not yet cached: git diff
  • View cached changes: git diff --cached
  • See all cached and uncached changes: git diff HEAD
  • Show a summary instead of the whole diff: git diff --stat

Show the difference between the staging area and the workspace:

$ git diff [file]

Show the difference between the staging area and the last commit:

$ git diff --cached [file]

$ git diff --staged [file]

Show the difference between two commits:

$ git diff [first-branch]...[second-branch]

git status shows you the changes since your last commit update or written to the cache, while git diff shows you what those changes were, line by line.

git commit

The git commit command adds the contents of the staging area to the local repository.

Submit the staging area to the local repository:

git commit -m [ message ]

[message] can be some remarks.

Submit the specified files in the staging area to the workspace area:

$ git commit [ file1 ] [ file2 ] ... -m [ message ]   

-a parameter setting does not need to execute the git add command after modifying the file, just submit it directly –

$ git commit -a

Set user information when submitting code:

Before we start, we need to set the submitted user information, including username and email:

$ git config --global user.name 'techinplanet' 
$ git config --global user.email [email protected].com

If the --global parameter is removed, it is only valid for the current repository.

Submit changes:

Next we can add all the changes to file from the staging area to the local repository.

In the following example, we use the -m option to provide commit comments on the command line.

$ git add myfile.txt
$ git status -s
A  README
A  myfile.txt
$ git commit -m 'my first commit'
[master (root-commit) d32cf1f] my first commit
 2 files changed, 4 insertions(+)
 create mode 100644 README
 create mode 100644 myfile.txt

Now we have recorded the snapshot. If we execute git status again:

$ git status
 # On branch master 
nothing to commit ( working directory clean )

The above output shows that we haven’t made any changes since the last commit. It is a “working directory clean”, which translates to a clean working directory.

If you don’t set the -m option, Git will try to open an editor for you to fill in the commit information. If Git can’t find relevant information in your configuration for it, it will open vim by default. The screen will look like this:

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
# modified:   myfile.txt
#
~
~
".git/COMMIT_EDITMSG" 9L, 257C

Git also allows you to skip this step with the -a option if you find the git add commit cache process too cumbersome. The command format is as follows:

git commit -a

We first modify the myfile.txt file to the following:

This is the text file

Then execute the following command:

$ git commit -am 'myfile.txt is modified'
 [ master 71ee2cb ] myfile.txt is modified
 1 file changed , 1 insertion ( +)

git reset

The git reset command is used to roll back the version. We can specify the version number to which we want rollback.

The syntax of the git reset command is as follows:

git reset [--soft | --mixed | --hard] [HEAD]  

–mixed is the default. So this parameter can be omitted.

The file used to reset the temporary storage area is the same as the last commit and the content of the workspace file remains unchanged.

git reset [ HEAD ] 

Example:

$ git reset HEAD^ # Roll back everything to the previous version   
$ git reset HEAD^ myfile.txt   # Roll back the version of the myfile.txt file to the previous version   
$ git reset 052e # Roll back to the specified version                       

The –soft parameter is used to fall back to a certain version:

git reset --soft HEAD

Example:

$ git reset --soft HEAD~3 # Go back to the previous version   

The –hard parameter undoes all uncommitted modifications in the workspace. It returns both the staging area and the workspace to the previous version, and deletes all previous information submissions:

git reset --hard HEAD

Example:

$ git reset --hard HEAD~3 # Go back to the previous version   
$ git reset --hard bae128   # Go back to all the information before the rollback point of a certain version. 
$ git reset --hard origin/master     # revert the local state to the same as the remote  

Note: Use the –hard parameter with caution , it deletes all information before the fallback point.

HEAD description:

  • HEAD indicates the current version
  • HEAD^ previous version
  • HEAD^^ previous version
  • HEAD^^^ previous version
  • And so on…

Can be expressed using ~ numbers

  • HEAD~0 indicates the current version
  • HEAD~1 previous version
  • HEAD^2 previous version
  • Previous version on HEAD^3
  • And so on…

git reset HEAD

The git reset HEAD command is used to cancel cached content.

We first modify the README file, the content is as follows:

# This is README File

The myfile.txt file is modified to:

This is the text file
This is the text file

Now that the two files are modified, they are both submitted to the cache area. We now want to cancel the cache of one of them. The operation is as follows:

$ git status -s
    M README
    M myfile.txt
$ git add . 
$ git status -s
    M README
    M myfile.txt
$ git reset HEAD myfile.txt 
 Unstaged changes after reset : 
    M myfile.txt
$ git status -s
    M README
    M myfile.txt

Now when you execute git commit, only the changes in the README file will be submitted, but myfile.txt won’t –

$ git commit - m 'files modified'
 [ master f50cfda ] files modified
 1 file changed , 1 insertion (+) 

$ git status - s
    M myfile.txt

It can be seen that the modification of the myfile.txt file has not been submitted.

At this point we can submit the changes to myfile.txt using the following command:

$ git commit - am 'modify myfile.txt file'
 [ master 760f74d ] modify myfile.txt file
 1 file changed , 1 insertion ( +)
 
$ git status
On branch master
nothing to commit , working directory clean

In short, do a git reset HEAD to cancel the cache added by a previous git add, but not included in the next commit snapshot.

git rm

The git rm command is used to delete files.

If you simply manually delete the file from the working directory, you will be prompted with Changes not staged for commit when you run git status .

git rm deletes files in the following forms:

Delete the file from the staging area and workspace:

git rm <file>

The following example deletes the myfile.txt file from the staging area and workspace:

git rm myfile.txt 

If the deletion has been modified before and has been placed in the staging area, the forced deletion option -f must be used .

Forcibly delete the modified myfile.txt file from the staging area and workspace:

git rm -f myfile.txt 

If you want to remove a file from the staging area, but still want to keep it in the current working directory, use the –cached option. In other words, just remove it from the tracking list –

git rm --cached <file>

The following example deletes the myfile.txt file from the staging area:

git rm --cached myfile.txt

Example

Delete the myfile.txt file:

$ git rm myfile.txt 
rm 'myfile.txt'
$ ls
README

The file is removed from the staging area, but the workspace remains:

$ git rm --cached README 
rm 'README'
$ ls
README

It can be deleted recursively. That is, all subdirectories and files will be deleted too:

git rm –r * 

git mv

The git mv command is used to move or rename a file, directory or symlink.

git mv [file] [newfile]

If the new filename already exists, but you want to rename it anyway, use the -f parameter:

git mv -f [file] [newfile]

We can add a README file (if it doesn’t exist):

$ git add README 

Then rename it:

$ git mv README README.md
$ ls
README.md

git log

You can use git log command to view the commit history. This is useful when you committed sever updates and wants to review them.

$ git log
commit d5e9fc2c811e0ca2b2d28506ef7dc14171a207d9 (HEAD -> master)
Merge: c68142b 7774248
Author: techinplanet <[email protected]>
Date:   Fri Jan 15 15:55:58 2022 +0800

    Merge branch 'change_site'

commit c68142b562c260c3071754623b08e2657b4c6d5b
Author: techinplanet <[email protected]>
Date:   Fri Jan 15 15:52:40 2022 +0800

    Modify the code

commit 777424832e714cf65d3be79b50a4717aea51ab69 (change_site)
Author: techinplanet <[email protected]>
Date:   Fri Jan 15 15:49:22 2022 +0800

    changed the runoob.php

commit c1501a244676ff55e7cccac1ecac0e18cbf6cb00
Author: techinplanet <[email protected]>
Date:   Fri Jan 15 15:35:40 2022 +0800

More git log commands can be viewed at: http://git-scm.com/docs/git-log

git blame

If you want to view the modification record of the specified file, you can use the git blame command –

git blame <file>

git remote

The git remote command is used for operations in remote repositories.

Show all remote repositories:

git remote -v

Let’s load the remote workspace first, and then view the information:

$ git clone https://github.com/akamittal/akashmittal-articles.git
$ cd akashmittal-articles
$ git remote -v
origin  https://github.com/akamittal/akashmittal-articles.git (fetch)
origin  https://github.com/akamittal/akashmittal-articles.git (push)

origin is the alias of the remote address.

Display information about a remote repository:

git remote show [remote]

Example –

$ git remote show https://github.com/akamittal/akashmittal-articles.git
* remote https://github.com/akamittal/akashmittal-articles.git
  Fetch URL: https://github.com/akamittal/akashmittal-articles.git
  Push  URL: https://github.com/akamittal/akashmittal-articles.git
  HEAD branch: master
  Local ref configured for 'git push':
    master pushes to master (local out of date)

Add remote repository:

git remote add [shortname] [url]

shortname is the local repository, for example:

# Commit to Github 
$ git remote add origin [email protected]:akamittal/akashmittal-articles.git
$ git push -u origin master

Other related commands:

git remote rm name   # Delete the remote workspace 
git remote rename old_name new_name   # Modify the workspace name

git fetch

The git fetch command is used to fetch repositories from a remote.

After the command is executed, you need to execute git merge to merge remote branch with your branch.

Use the below command to pull data from the remote repository and try to merge into the current branch:

git merge

This command is to be executed immediately after executing git fetch.

Assuming you have a remote repository configured and you want to fetch updated data, you can first execute:

git fetch [alias]

The above command tells Git to fetch the data it has and you don’t have. Then you can execute:

git merge [alias]/[branch]

The above command merges any updates on the server (assuming someone pushed to the server at this point) into your current branch.

Let’s take an example. Update README file on a remote repository. You an edit it in Github editor.

Then we update the modifications locally.

$ git fetch origin
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From github.com:myusername/my-repository
   04758ahd..shkejr34  master     -> origin/master

The above information “04758ahd..shkejr34 master -> origin/master” indicates that the master branch has been updated. We can use the following command to synchronize the update to the local:

$ git merge origin/master
Updating 04758ahd..shkejr34
Fast-forward
 README.md | 1 +
 1 file changed, 1 insertion(+)

View the contents of the README.md file:

$ cat README.md 

git pull

The git pull command is used to fetch the code from the remote and merge the local version.

git pull is actually shorthand for git fetch and git merge FETCH_HEAD .

The command format is as follows:

git pull <remote hostname> <remote branch name>:<local branch name> 

Example

Update operation:

$ git pull
$ git pull origin

Pull the master branch of the origin of the remote host and merge it with the local branch.

git pull origin master:localbranch

If the remote branch is to be merged with the current branch, then the part after the colon can be omitted.

git pull origin master

The above command means to fetch the origin/master branch and merge it with the current local branch.

The pull operation above is represented by fetch as:

$ git remote -v   # View information 
origin https://github.com/akamittal/akashmittal-articles.git ( fetch) 
origin https://github.com/akamittal/akashmittal-articles.git ( push)

$ git pull origin master
From https://github.com/akamittal/akashmittal-articles.git
 * branch            master     -> FETCH_HEAD
Already up to date.

The above command indicates that the origin/master branch is retrieved and merged with the local master branch.

git push

The git push command is used to upload and merge from the local branch version to the remote.

The command format is as follows:

git push <remote hostname> <local branch name>:<remote branch name> 

If the local branch name is the same as the remote branch name, the colon can be omitted:

git push <remote hostname> <local branch name> 

Example

The following command pushes the local master branch to the origin master branch.

$ git push origin master

equal to:

$ git push origin master:master

If there is a difference between the local version and the remote version, but you want to force the push, you can use the --force parameter:

git push --force origin master

To delete the branch of the host, you can use the --delete parameter. The following command will delete the master branch of the host:

git push origin --delete master

Conclusion

In this comprehensive article we saw different git commands and their explanation in detail. These commands are used for code sharing, version management and code management among teams.

Leave a Reply

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