How to Connect Git to Github?

In this article we will see the process to connect git to GitHub.

How to Connect Git to Github?

Github is a very popular version control system. We can use it to store our local git commits and access them anywhere with an internet connection.

To push a repo to github

  • Visit github.com
  • Login with your credentials
  • Click the new repository button which will bring you to a page like this

How to Connect Git to Github_Pic1

  • After filling in the required fields create the repository
  • Now click “Push an existing repository”
  • In the git terminal on your machine
    $ git remote add origin https://github.com/username/new_repo

$ git remote add origin https://github.com/username/new_repo

  • Enter your password then set the branch to main
    $ git branch -M main

● Enter your password then set the branch to main $ git branch -M main

  • Push the branch

        $ git push -u origin master

How to connect git to Github

  • After successful pushing, we will have

Git Discarding Local Changes & Skipping the Staging Area

In this article we will see how to discard local changes and how to skip the staging area.

Git Discarding Local Changes & Skipping the Staging Area

We will learn 2 things in this article

  1. Discard local changes
  2. Skip staging area

So let’s see one by one.

Discard Local Changes:

Some time we might need to discard the changes and go back to the previous version of the code. To do that we will create a new file and commit.

$ cat>file_name 

Use the above command to create a file and add some text to it. After we are done, use ctrl+S to save it.

Git Discarding Local Changes & Skipping the Staging Area_One

Content in the file. (Opened new_file.txt)

Git Discarding Local Changes & Skipping the Staging Area_Two

Now commit the changes using

 $ git commit -am

Git Discarding Local Changes & Skipping the Staging Area_Three

Let’s remove and add some other lines to the txt file.

Git Discarding Local Changes & Skipping the Staging Area_Four

Now we can see the changes using

$ git status -s

We can see that there are some changes made to the file we created.

Now we want to restore this file to its previous version(where it was empty). To do so we need to use the command

$ git restore file_name
Git Discarding Local Changes & Skipping the Staging Area_Five

This should restore our file back. Now when we check the status again

$ git status -s

To confirm let’s see the text file contentsGit Discarding Local Changes & Skipping the Staging Area_Six

Skip staging area:

Staging area is the place where all modified files are shown. That is why it is not advisable to skip the staging area but if you are sure that there are no unnecessary files you can skip them.

Normally we would add the files to the staging area using

$ git add

Git Discarding Local Changes & Skipping the Staging Area_Seven

And then we commit the changes using

$ git commitGit Discarding Local Changes & Skipping the Staging Area_EightHowever to skip the staging area we can do it by directly committing

Use the command

$ git commit -a

This will push all the files

To add the message use the command

$ git commit -am “message” Git Discarding Local Changes & Skipping the Staging Area_Nine

How to Create a Git Repo?

In this article we are going to see how we can create a git repo.

How to Create a Git Repo?

There can be two cases while creating a git repo.

  1. Creating a new repo from scratch
  2. Creating a repo from an existing directory

To create a new repo from scratch follow the below steps-

  • Create a new directory from the menu or by using the command.
    $ mkdir dir_name

This will create a directory in the working folder with the name specified.

How to Create Git Repo_Pic1

  • Navigate into the new directory using the command
    $ cd dir_name

How to Create Git Repo_Pic2.png

  • Now to create a repo use the command
    $ git init

How to Create Git Repo_Pic3.png

This will create a git repo in that directory. From there you can add files to the git repo.

  • After adding your files commit by the command
     $ git commit

How to Create Git Repo_Pic4

Now, to create a repo for a pre-existing project,

  • Navigate into the directory using cd command
  • Now to create the repo use the command
    $ git init
  • Add the files to the repo using
    $ git add
  • Commit the changes using
    $ git commit
How To Change Git Remote Origin

How To Change Git Remote Origin | What is Git Remote? | Git Remote Add Origin

Did you change your remote git repository name? Do you want to move a remote repository to another location? Both these operations will make you push to your remote origin on a daily basis.

You can be rescued from such cases by using the git commands that suit the related concept here git remote set-url command will help you most. It permits you to change the URL of a remote repository. In this tutorial, we have explained what is git remote and how to change git remote origin easily?

What is a Git Remote?

A Git remote is a pointer that links your local version of a repository to a remote repository. A Git repository can hold many remotes linked to it and mostly they have only one remote. Repositories with more than one remote are normally linked to various development environments like testing, staging, or production.

When you modify the repository name or move it to another hosting platform, you’ll require to update your remote URLs. Let’s look at the process of changing the Git Remote URL from the below modules.

Change Git Remote URL

In order to change the URL of a Git remote, you have to use the “git remote set-url” command and specify the name

of the remote as well as the new remote URL to be changed.

$ git remote set-url <remote_name> <remote_url>

For example, let’s say that you want to change the URL of your Git origin remote.

In order to achieve that, you would use the “set-url” command on the “origin” remote and you would specify the new URL.

$ git remote set-url origin https://git-repo/new-repository.git

Change Git Remote URL set-url

Congratulations, you successfully changed the URL of your Git remote!

In order to verify that the changes were made, you can use the “git remote” command with the “-v” option (for verbose)

$ git remote -v

Change Git Remote URL list-remotes

Changing Git Remote to SSH

In some cases, you may have configured your Git repository to use SSH key-based authentication.

If you want to change your Git origin remote using SSH authentication, you can use the same “git remote set-url” command but you will have to use the SSH URL in order to connect.

$ git remote set-url <remote_name> <ssh_remote_url>

The SSH URL usually takes the following form :

SSH URL : git@<repo_url>:<url>/<git_repository>.git

For example, if your repository was configured on Github, you would use the following command to change your remote.

$ git remote set-url origin git@github.com:user/repository.git

Changing Git Remote to SSH git-remote-ssh

If you are having trouble identifying the URL of your Git remote on Github, the next section might be helpful.

Getting Git Remote URL on GitHub

If you need to quickly find the URL of your Git remote on Github, you first need to select your repository by navigating to your repository list.

> https://github.com/<user>/repositories

Getting Git Remote URL on GitHub repo-github

Under your repository list, select the repository you are interested in.

Now that your repository is select, locate the “Clone or Download” option on the right corner of your screen.

Also Check: How To Clone a Git Repository

When clicking on it, you should be presented with the URL of your Git repository.

Getting Git Remote URL on GitHub clone

You can now use the “git remote set-url” command in order to set your Git remote URL properly (using the previous section).

Conclusion

In this tutorial, you learned how you can easily change your Git remote URL (commonly named origin) by using the “git remote set-url” command.

You also learned that you can change it using a password-protected SSH address.

If you are looking for an easy way to generate SSH keys for Git, you should take a look at our tutorial.

SSH key authorization is preferred over password authentication if you have a repository with a large activity.

If you are interested in Git or in Software Engineering, we have a complete guide dedicated to it on the website, so make sure to check it out!

How To Git Reset to HEAD

How To Git Reset to HEAD | What is Git HEAD? | How to Reset Git Head to Latest Commit

Developers create files, branches, add them, and even stage them for commits while working on a project in Git. At some points, you decide to do some modifications to files or add lines or delete lines from your git files and you require to go back to the files that you had finally.

The powerful tool and technique to make it possible for developers is “reset to HEAD”. So, this tutorial is made for explaining completely how you can easily reset to HEAD on Git with examples. For better learnings on Git go for the Git commands tutorial thoroughly.

What is Git HEAD?

Git HEAD refers to the current commit you are observing. By default, you’ll see the tip of the master branch on a repository, except the main branch of your repository has a strange name. The master branch tip is the most recent commit on the main branch of your codebase.

Git Hard Reset to HEAD

When resetting files on Git, you essentially have two options: you can either hard reset files or soft reset files.

In this section, we are going to describe how you can hard reset files on Git.

In order to hard reset files to HEAD on Git, use the “git reset” command with the “–hard” option and specify the HEAD.

$ git reset --hard HEAD       (going back to HEAD)

$ git reset --hard HEAD^      (going back to the commit before HEAD)
$ git reset --hard HEAD~1     (equivalent to "^")

$ git reset --hard HEAD~2     (going back two commits before HEAD)

The purpose of the “git reset” command is to move the current HEAD to the commit specified (in this case, the HEAD itself, one commit before HEAD, and so on).

What is the “–hard” option used for?

The “–hard” option is used in order to reset the files of the index (or the staging area) and of the working directory.

Using “–hard”, you will be left with the untracked files of your working directory.

Look Some More Git Tutorials: 

Hard Reset Examples

In order to understand the “hard reset” use cases, let’s have some quick examples.

When trying to reset files, the first command that you want to launch is the “git log” command.

Using the “git log” command, you will be able to have a global understanding of your current Git branch and its commits.

$ git log --oneline --graph

* 802a2ab (HEAD -> feature, origin/feature) feature commit
* 7a9ad7f (origin/master, master) version 2 commit
* 98a14be Version 2 commit
* 53a7dcf Version 1.0 commit
* 0a9e448 added files
* bd6903f first commit

As you can see in the example, the “feature” branch is one commit ahead of the HEAD of the master branch.

In order to hard reset to the commit right before HEAD, use “git reset” with the “–hard” option and specify HEAD^.

$ git reset --hard HEAD^

HEAD is now at 7a9ad7f version 2 commit

As you can see, the HEAD of the release branch is now pointing to the second commit: we actually have reset to the commit before HEAD.

$ git log --oneline --graph

* 7a9ad7f (HEAD -> feature, origin/master, master) version 2 commit
* 98a14be Version 2 commit
* 53a7dcf Version 1.0 commit
* 0a9e448 added files
* bd6903f first commit

Undoing hard reset to HEAD

Using the last section, you successfully moved the HEAD of your feature branch to one commit before HEAD.

But what if you undo your changes, meaning going back one commit after HEAD?

To undo a hard reset on Git, use the “git reset” command with the “–hard” option and specify “HEAD@{1}”

$ git reset --hard HEAD@{1}

Using the example that we used before, that would give us the following output

$ git reset --hard HEAD@{1}

HEAD is now at 802a2ab feature commit

$ git log --oneline --graph

* 802a2ab (HEAD -> feature, origin/feature) feature commit
* 7a9ad7f (origin/master, master) version 2 commit
* 98a14be Version 2 commit
* 53a7dcf Version 1.0 commit
* 0a9e448 added files
* bd6903f first commit

Note: You might not be able to undo your changes if you reset your commits quite a long time ago. In fact, Git uses a garbage collector that ensures that the local repository is optimized.

Git Soft Reset to HEAD

To soft reset files to HEAD on Git, use the “git reset” command with the “–soft” option and specify the HEAD.

$ git reset --soft HEAD       (going back to HEAD)

$ git reset --soft HEAD^      (going back to the commit before HEAD)
$ git reset --soft HEAD~1     (equivalent to "^")

$ git reset --soft HEAD~2     (going back two commits before HEAD)

Contrary to the hard reset, the soft reset won’t alter the working directory and the index.

As a consequence, the changes done between the original HEAD and the current HEAD will be staged.

Back to the example, we took before, let’s have a quick look at the “feature” branch.

$ git log --oneline --graph

* 802a2ab (HEAD -> feature, origin/feature) feature commit
* 7a9ad7f (origin/master, master) version 2 commit
* 98a14be Version 2 commit
* 53a7dcf Version 1.0 commit
* 0a9e448 added files
* bd6903f first commit

In order to move the HEAD to one commit before, use the “git reset” command with the “–soft” option and specify “HEAD^”

$ git reset --soft HEAD^             (or HEAD~1)

This time, the staging area will be filled with the changes done between commit 7a9ad7f and commit 802a2ab.

Let’s have a look at the changes using the “git status” command.

$ git status

On branch feature
Your branch is behind 'origin/feature' by 1 commit and can be fast-forwarded.
  (use "git pull" to update your local branch)

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   file-feature

Combining commits using soft reset

One popular usage of the soft reset command is to combine many different commits into a single one.

On your current branch, let’s have a look at all the commits currently done.

$ git log --oneline --graph

* af2653a (HEAD -> feature) Commit 3
* 2b9606a Commit 2
* 6f41547 Commit 1
* 87c800f Original commit

In order to combine the last three commits, let’s move the HEAD using the “git reset” command with the “–soft” option.

$ git reset --soft HEAD~3

$ git status

On branch feature
Your branch is behind 'origin/feature' by 3 commits, and can be fast-forwarded.
  (use "git pull" to update your local branch)

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   a.txt
        new file:   b.txt
        new file:   c.txt

Now that commits are rollbacked, let’s commit the files using the “git commit” command.

$ git commit -m "Combining commits using git reset"

$ git log --oneline --graph

* 391172d (HEAD -> feature) Combining commits using git reset
* 87c800f Original commit

Great! Your commits are now combined in a single commit.

Conclusion

In this tutorial, you learned how you can easily reset your files to HEAD on Git using the “git reset” command.

We also described the difference between the hard reset and soft reset: basically discarding (hard) or keeping them in your staging area in order to re-commit them later on (soft)

If you are interested in Git or in software engineering in general, we have a complete section dedicated to it on the website, so make sure to check it out!

How To Undo Git Add Command

How To Undo Git Add Command | Git undo Add Operation | How to Undo Git Add before Commit?

Git does not automatically involve changes in a commit: they have to be explicitly added to the next commit, with the git add command. But, in any instance, you may need to undo a “git add” operation that you just made.

Also Refer: Git Commands

So this tutorial is all about undoing the git add command. Go through the following modules and completely learn how you can easily undo a Git add command with ease. With the help of these methods, your git files can be back in your working directory.

Git undo Add Operation

As a picture is worth a thousand words, here is a recap of all the operations that you can perform to undo a Git add operation.

How To Undo Git Add Command git-undo-add-schema

If you want to know more details, you should go through the detailed examples below.

Also Check: How To Undo Last Git Commit

Determine your current Git version

Like with any other software tool, Git changes and adds new commands on major releases.

As a result, if you are using an old version of Git, you might not be able to run some of the commands.

In order to know your current Git version, you can execute the “git” command followed by the “–version” option.

$ git --version

Determine your current Git version git-version

The “git restore” command was introduced in Git 2.23, so if you are using an older version, make sure to update your current Git installation.

$ git update

$ git update-git-for-windows

Determine your current Git version update-git

 

How to undo git add before commit?

While working in Git, the files to be committed are found in the staging area. Now, assume that you have added an unnecessary file to the staging area. To remove only a single file which is unuseful from the staging area should run the command below:

git reset <file-name>

If you want to remove all the files from the staging area, then you should run the following command:

git reset

As you can perceive, git reset is utilized for undoing git add. Running only git reset without defining the file name is particularly helpful when you are inadequate to list all the actual files one by one.

Undo Git Add using restore

The simplest way to undo your git add command is to use the “git restore” command with the “–staged” option and specify the file you want to unadd.

$ git restore --staged <file>

As an example, let’s say that you are on a branch named “feature” and that you have recently added a new file to your staging area.

$ git status

Undo Git Add using restore git-status-command

In order to bring back the file to the working directory, we can execute the “git restore” command with the “–staged” option.

$ git restore --staged another-file

Undo Git Add using restore git-undo-add-operation

Congratulations, you have successfully undone your “git add” command using the restore one!

Now you can modify your file, add it again and commit it if you want.

The “–staged” option means that you essentially want to unstage the file from your Git index, but that you want to keep the modifications done to the file.

So what happens if you don’t specify the “–staged” option?

As specified in the “git restore” documentation, by default, the working tree will be restored, meaning that you discard changes from your working area.

Note that the file needs to be tracked by Git in order to be restored: if it is part of the untracked files, you won’t be able to “restore” it.

As an example, let’s say that you have modified a file but the changes are yet to be committed to the staging area.

Undo Git Add using restore git-undo-working-directory

Note: Be extra careful with the “git restore” command when files are in your working directory, you will lose all your changes and there is no going back.

$ git restore another-file

$ git status
On branch feature
nothing to commit, working tree clean

Awesome, your file went back to the state it was before doing any modifications to it.

Undo Git Add using reset

Undoing a recent Git “add” operation can also be achieved by using the “git reset” command followed by the file that you want to “unstage“.

$ git reset <file>

$ git reset -- <file>                    (is an equivalent syntax)

$ git reset HEAD <file>                  (achieves the same result)

As an example, let’s try to undo a Git “add” operation on a file named “file” that we just added.

Undo Git Add using reset git-status-command-2-1

In this case, to undo this accidental Git “add” operation, we are going to use the “git reset” command, specify the HEAD (the most recent commit) and the name of the file.

$ git reset HEAD file

Unstaged changes after reset:
M       file

As you can see, our files were correctly unstaged which is the result that we wanted to achieve.

A simple “git status” command can be used in order to verify our current state.

Undo Git Add using reset git-reset-command

Congratulations, you have successfully undone an “add” operation in your repository!

Erasing your local changes using git checkout

Now that your file is back to your working directory, you can choose to erase all the modifications that you have performed.

To undo all local changes and go back to your file original version, you have to use the “git checkout” command followed by double hyphens and the name of the file.

$ git checkout -- <file>

As an example, let’s use the file that we unstaged in the previous section.

If we want to remove the modifications done to this file, we execute the command described just above.

$ git checkout -- file

Erasing your local changes using git checkout git-checkout-command

As you can see, all modifications were “erased” and the file is back to its original state.

Conclusion

In this tutorial, you learned how you can easily “undo” a Git “add” operation. Depending on your Git version, you can use two commands: the “restore” one, or the “reset” one.

Additional options have to be used depending on the location of your file: “–staged” if it is in the staging area or no options if it is in your working directory.

If you are interested in Git, we have a complete section dedicated to it on the website, so make sure to check it out!

How To Add and Update Git Submodules

How To Add and Update Git Submodules | Definition of Submodule

If you are developing a large project then you need to be familiar with this important concept called Git submodules. Git submodules permit you to have a git repository as a subdirectory of different git repositories. Just these are a reference to another repository at a particular snapshot in time.

Do Check: GIT Commands

Also, Git submodules allow a Git repository to incorporate another versioned project within an existing project and track the version history of external code. In this tutorial, we are discussing how easily add, update and remove Git submodules on your main project can be done. Apart from this, we will describe concepts about Git submodules

What is a Submodule?

A Submodule is a Git Repository inside another Git Repository. This embedded Git Repository can be run separately and will have its individual Git workflow. This embedded repository can also be used as a Submodule for various other repositories without generating new files from scratch for each repository.

When should you use a git submodule?

By using the Git submodules, you can easily maintain strict version management over your external dependencies. The furnished points are some of the best use cases for git submodules:

  • When you have a component that isn’t updated very often and you want to track it as a vendor dependency.
  • When an external component or subproject is changing too fast or upcoming changes will break the API, you can lock the code to a specific commit for your own safety.
  • When you are delegating a piece of the project to a third party and you want to integrate their work at a specific time or release. Again this works when updates are not too frequent.

Do Refer: How To Create and Apply Git Patch Files

Add a Git Submodule

The first thing you want to do is to add a Git submodule to your main project.

In order to add a Git submodule, use the “git submodule add” command and specify the URL of the Git remote repository to be included as a submodule.

Optionally, you can also specify the target directory (it will be included in a directory named like the remote repository name if not provided)

$ git submodule add <remote_url> <destination_folder>

When adding a Git submodule, your submodule will be staged. As a consequence, you will need to commit your submodule by using the “git commit” command.

$ git commit -m "Added the submodule to the project."

$ git push

As an example, let’s pretend that you want to add the “project” repository as a submodule on your project into a folder named “vendors”.

To add “project” as a submodule, you would run the following command at the root of your repository

$ git submodule add https://github.com/project/project.git vendors

Cloning into '/home/user/main/project'...
remote: Enumerating objects: 5257, done.
remote: Total 5257 (delta 0), reused 0 (delta 0), pack-reused 5257
Receiving objects: 100% (5257/5257), 3.03 MiB | 3.38 MiB/s, done.
Resolving deltas: 100% (3319/3319), done.

When adding a new Git submodule into your project, multiple actions will be performed for you:

  • A folder is created in your Git repository named after the submodule that you chose to add (in this case “vendors”);
  • A hidden file named “.gitmodules” is created in your Git repository: this file contains the references to the remote repositories that you cloned as submodules;
  • Your Git configuration (located at .git/config) was also modified in order to include the submodule you just added;
  • The submodule you just added is marked as a change to be committed in your repository.

Add a Git Submodule add-submodule-1

Pull a Git Submodule

In this section, we are going to see how you can pull a Git submodule as another developer on the project.

Whenever you are cloning a Git repository having submodules, you need to execute an extra command in order for the submodules to be pulled.

If you don’t execute this command, you will fetch the submodule folder, but you won’t have any content in it.

To pull a Git submodule, use the “git submodule update” command with the “–init” and the “–recursive” options.

$ git submodule update --init --recursive

Going back to the example we described before: let’s pretend that we are in a complete new Git repository created by our colleague.

In its Git repository, our colleague first starts by cloning the repository, however, it is not cloning the content of the Git submodule.

To update its own Git configuration, it has to execute the “git submodule update” command.

$ git submodule update --init --recursive

Submodule 'vendors' (https://github.com/project/project.git) registered for path 'vendors'
Cloning into '/home/colleague/submodules/vendors'...
Submodule path 'vendors': checked out '43d08138766b3592352c9d4cbeea9c9948537359'

As you can see, pulling a Git submodule in our colleague Git repository detached the HEAD at a given commit.

The submodule is always set to have its HEAD detached at a given commit by default: as the main repository is not tracking the changes of the submodule, it is only seen as a specific commit from the submodule repository.

Steps on how to Update Git Submodules

For updating the Git submodules in your workspace with the latest commits on the server please follow the below steps carefully:

  • Clone the remote repository, if you haven’t already.
  • Issue a git submodule update –remote command.
  • Add any new files pulled from the repository to the Git index.
  • Perform a git commit.
  • Push back to origin.

Update a Git Submodule

In some cases, you are not pulling a Git submodule but you are simply looking to update your existing Git submodule in the project.

In order to update an existing Git submodule, you need to execute the “git submodule update” with the “–remote” and the “–merge” option.

$ git submodule update --remote --merge

Using the “–remote” command, you will be able to update your existing Git submodules without having to run “git pull” commands in each submodule of your project.

When using this command, your detached HEAD will be updated to the newest commit in the submodule repository.

Given the example that we used before when updating the submodule, we would get the following output:

$ git submodule update --remote --merge

Updating 43d0813..93360a2
Fast-forward
 README.md | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
Submodule path 'vendors': merged in '93360a21dc79011ff632b68741ac0b9811b60526'

Git Submodules Update Example

For executing the update git submodules example on your local machine, you can make use of the following commands:

submodule@example:~$ git clone --recurse-submodules https://gitlab.com/cameronmcnz/surface.git
submodule@example:~$ cd sur*
submodule@example:~$ git submodule update --remote
submodule@example:~$ git add .
submodule@example:~$ git commit -m "git submodule updated"
submodule@example:~$ git push origin

Fetch new submodule commits

In this section, you are looking to update your Git repository with your commits coming from the submodule repository.

First, you may want to fetch new commits that were done in the submodule repository.

Let’s say for example that you want to fetch two new commits that were added to the submodule repository.

To fetch new commits done in the submodule repository, head into your submodule folder and run the “git fetch” command first (you will get the new submodule commits)

$ cd repository/submodule 

$ git fetch

Now, if you run the “git log” command again, you will be able to see the new commits you are looking to integrate.

$ git log --oneline origin/master -3

93360a2 (origin/master, origin/HEAD) Second commit
88db523 First commit
43d0813 (HEAD -> master) Initial commit

Now, in order for your submodule to be in line with the newest commits, you can run the “git checkout” command and specify the SHA that you want to update your submodule to (in this case 93360a2)

$ git checkout -q 93360a2

Great! Your HEAD is now aligned with the newest commits from the submodule repository.

You can now go back to your main repository and commit your changes for other developers to fetch those new commits.

$ cd repository

$ git add.

$ git commit -m "Added new commits from the submodule repository"

$ git push

Remove Git submodules

In this section, we are going to see how you can effectively remove a Git submodule from your repository.

In order to remove a Git submodule from your repository, use the “git submodule deinit” command followed by the “git rm” command and specify the name of the submodule folder.

$ git submodule deinit <submodule>

$ git rm <submodule>

When executing the “git submodule deinit” command, you will delete the local submodule configuration stored in your repository.

As a consequence, the line referencing the submodule will be deleted from your .git/config file.

The “git rm” command is used in order to delete submodules files from the working directory and remaining .git folders.

Configuring submodules for your repository

In some cases, you may want to have additional logging lines whenever you are executing “git status” commands.

Luckily for you, there are configuration properties that you can tweak in order to have more information about your submodules.

Submodule summary

In order to have a submodule summary when executing “git status”, execute the “git config” command and add the “status.submoduleSummary” option.

$ git config --global status.submoduleSummary true

As a consequence, you will be presented with more information when executing “git status” commands.

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

  new file:   .gitmodules
  new file:   <submodule>

Submodule changes to be committed:

* <submodule> 0000000...ae14a2 (1):
  > Change submodule name

Detailed diff for submodules

If you configured your Git to have the submodule summary as explained in the previous section, you should now have a customized way to see the differences between submodules.

However, in some cases, you want to get more information about the commits that might have been done in your submodules folder.

For the “git diff” command to have detailed information about your submodules, use the “git config” command with the “diff.submodule” parameter set to true.

$ git config --global diff.submodule log

Now, whenever you are executing the “git diff” command, you will be able to see the commits that were done in the submodules folder.

$ git diff

Submodule <submodule> 0000000...ae14a2:
  > Submodule commit n°1
  > Submodule commit n°2

Conclusion

In this tutorial, you learned what submodules are and how you can use them in order to have external repositories in your main project repository. Also, more about how to add and update Git submodules using the dedicated “git submodule” commands: “git submodule add” and “git submodule update“.

Finally, you have seen that it is possible to tweak your Git configuration in order to get more information about your Git repository.

How To Git Stash Changes

How To Git Stash Changes | Learn Git Stash Apply, Pop, Clear, Show, Drop

Guys who are new to Git should aware of the git stash command as it is the most important command in Git. It is performed to protect all the changes made with the current working directory and to go back to the last commit done on the branch (also known as HEAD).

In this tutorial, we guys will definitely come to know about git stash commands and how to do git stash changes in practical cases. Just make use of the available links and jump into the exact stuff you required to learn about Git stashing.

Introduction to Git Stash

In some cases, you need to change the branches however you are operating an unfinished part of your current project. In that situation, you don’t want to do a commit to half-done work. Here, Git stashing permits you to do so. The git stash command allows you to change branches without committing the current branch.

Also Check: Git Commands

The following image shows the properties and role of stashing concerning the repository and working directory.

git stash image

Usually, the meaning of stash is “store something safely in a hidden place.” The sense in Git is also the same for stash; Git temporarily saves your data safely without committing.

What is Stashing?

Stashing takes the messy state of your working directory, and temporarily saves it for further use. Several options are available with git stash. Some of the helpful options are provided here:

  • Git stash
  • Git stash save
  • Git stash list
  • Git stash apply
  • Git stash changes
  • Git stash pop
  • Git stash drop
  • Git stash clear
  • Git stash branch

Stashing changes come with a special set of Git commands intended to createdelete and apply stashes at will.

Do Check: How To Set Upstream Branch on Git

Create a Git stash

The easiest way to create a git stash is to simply run the “git stash” command without any parameters.

$ git stash

As a consequence, all the changes staged for commit in your current working directory will be saved on the side for later use.

$ git stash
Saved working directory and index state WIP on branch1: 808b598 Initial commit

As you can see, my working directory as well as my index was saved for the “branch1” which is the current name of my branch.

After the colons, you can see the hash of the HEAD commit as well as the commit message: this is the name of your stash.

In this case, no names were assigned to our stash which might not be very handy if you want to pop your stash later on.

Create a Git stash with a name

In order to create a git stash with a name, use the “save” command and specify the name of your stash.

$ git stash save "my_stash_name"

Back to the example, we gave before on the branch named “branch1”, we would run

$ git stash save "modified README.md"
Saved working directory and index state On branch1: modified README.md

Now, Git did not provide a default name (made by the last HEAD commit message) but it assigned a custom name to it.

Alternatively, you can use the “git stash push” command in order to create a stash with a name.

$ git stash push -m "modified the README.md" again
Saved working directory and index state On branch1: modified again the READ.me

Stashing your work

The git stash command takes your uncommitted changes (both staged and unstaged), saves them away for later use, and then reverts them from your working copy. For instance:

$ git status
On branch main
Changes to be committed:
   new file: style.css
Changes not staged for commit:
   modified: index.html

$ git stash
Saved working directory and index state WIP on main: 5002d47 our new homepage
HEAD is now at 5002d47 our new homepage

$ git status
On branch main
nothing to commit, working tree clean

Currently, you’re free to make changes, create new commits, switch branches, and perform any other Git operations; then come back and re-apply your stash when you’re ready.

Remark that the stash is local to your Git repository; stashes are not given to the server when you push.

Stash a specific file

Using the previous commands, you have stashed all the tracked files in your current working directory.

In some cases, you may want to stash a specific file in order to retrieve it later on.

To stash a specific file, use the “git stash push” command and specify the file you want to stash.

$ git stash push -m "message" <file>

For example, in order to stash the “README.md” file in our current working directory but keep changes done to the other files, we would run

$ git stash push -m "modified the README.md" README.md
Saved working directory and index state On branch1: modified README.md

However, the other tracked files that may be modified in your current working directory are untouched.

Stash untracked files

As you probably noticed before when creating stashes, stash only saves tracked files of your working directory by default.

But what if you wanted to stash untracked files of your current working directory?

In order to stash untracked files, add the “–include-untracked” option to your “git stash” initial command.

Alternatively, you can simply use the “-u” which is equivalent to the untracked longer version.

$ git stash --include-untracked
Saved working directory and index state WIP on branch1: 808b598 Initial commit

$ git stash -u

Specific Git Stash Branch

In some cases, you may want to stash your current changes into a specific branch.

Let’s say for example that you worked on the “master” branch for modifications, but you decide that your work may need a specific branch for integration.

This can be done with the “git stash branch” command.

$ git stash branch <branch_name>

$ git stash branch <branch_name> stash@{stash_index}

Let’s say for example that you want to stash your current changes in a branch named “branch1”, you would execute.

$ git stash branch branch1 stash@{0}

Switched to a new branch 'branch1'
On branch branch5
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")
Dropped stash@{0} (8bf64dd0e0045069bf3b3e7d9e34f5e5227aefa7)

As you can see, the stash is dropped at the end of the process, essentially removing it completely from the stash stack.

Git Stash Changes

We can trace the stashes and their changes. To view & understand the changes in the file before stash and after stash operation, execute the below command:

Syntax:

$ git stash show

This command will help you display the file that is stashed and changes made on them. Take a look at the following output:

git stash changes output

This result explains that there are two files that are stashed, and performed two insertions on them.

Tracking Git Stash Changes

Also, we can precisely track what changes are performed on the file. To show the changed content of the file, execute the below command:

Syntax:

$ git stash show -p

Here, -p stands for the partial stash. The given syntax will display the edited files and content, view the below output:

git stash track

The above output is bestowing the file name with changed content. It runs as same as the git diff command and also gives the exact output.

Also, look at the below video tutorial to gain more knowledge on how to git stash changes:

List Git stashes

Now that you have created some stashes, it is time for you to list the stashes that you just created.

In order to list Git stashes, use the “git stash list” command.

$ git stash list

stash@{0}: WIP on branch1: 808b598 Initial commit
stash@{1}: On branch1: modified README.md
stash@{2}: On branch1: modified again the READ.me

As you can see, stashes are given an index starting at zero.

When creating new stashes, items are added to the stack meaning that the most recent stash has the index 0 while the oldest stash is at the bottom of the stack.

This is closely related to the concept of a stack in software engineering. A link to an in-depth article is included if you are curious about stacks.

Apply Git stashes

Now that you have saved your Git stashes on the side, you might want to “take them out from the stack” and apply them to your current working directory.

In order to apply your Git stash to your current working directory, use the “git stash apply” command and specify the stash you want to apply.

If you don’t specify any arguments to the apply command, the top of the stack will be applied.

$ git stash apply stash@{stash_index}

$ git stash apply (shortcut for git stash apply stash@{0})

For example, in order to apply the changes done in the stash with index 1, we would run

$ git stash apply stash@{1}

Already up to date!
On branch branch1
Your branch is up to date with 'origin/branch1'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   README.md

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        file

By default, the stash applies command will list your current working directory after applying the corresponding stashes.

Now if you were to list your stashes, you would notice that applying your stash did not delete or remove the stash from the list.

$ git stash list

stash@{0}: WIP on branch1: 808b598 Initial commit
stash@{1}: On branch1: modified README.md
stash@{2}: On branch1: modified again the READ.me

If you want your stashes to be removed after applying them, you need to use the “git stash pop” command.

Pop Git stashes

So what is the difference between git stash pop and git stash apply?

The main difference is in the fact that the “git stash pop” applies your changes to your current working directory but it also deletes the stash from the stash stack.

To pop Git stashes, simply use the “git stash pop” command and specify the stash index you want to pop.

$ git stash pop stash@{stash_index}

Back to our previous stash example, this would give us

$ git stash pop stash@{1}

Already up to date!
On branch branch1
Your branch is up to date with 'origin/branch1'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   README.md

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        file

Dropped stash@{1} (1adaf79224dca78aa6568b1e8154cbc4f747042f)

See the difference in the last line of the example?

The stash was dropped and removed from the stack.

Show Git stash differences

When you create a stash, it is most likely to perform some commits before going back to your stashed content.

As a consequence, you may want to see the differences between your stash and the most recent commit of your branch (also called HEAD)

To show the differences between a stash and the most recent commit, use the “git stash show” command.

$ git stash show stash@{stash_index}

README.md | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)

As a consequence, you will be listed with the differences between files, the insertions, and the deletions done.

To see all the differences including content, add the “-p” option.

$ git stash show -p stash@{stash_index}

diff --git a/README.md b/README.md
index f25b874..1088f9a 100644
--- a/README.md
+++ b/README.md
@@ -1 +1,3 @@
-# private-repo
\ No newline at end of file
+The file was modified!

Drop Git stashes

In some cases, you may want to delete a Git stash entry from your stack.

In order to drop stashes, you have two options: with a drop or clear.

If you want to drop a specific stash from your stack, use the drop option and specify the stash index.

$ git stash drop stash@{stash_index}

For example, in order to delete stash with an index 1 from the previous example, you would run

$ git stash drop stash@{1}
Dropped stash@{1} (c11c6ae6c347d23dff8fbbf79d54a9e6e2e79b1c)

Drop all stashes using clear

If you want to delete all the Git stashes in your stack, you have to use the clear command.

$ git stash clear

Make sure that all your stashes were deleted with the list command.

$ git stash list

Conclusion

In this tutorial, you acquired basic knowledge about git stash such as how you can create stashes, delete stashes, and pop them in order to recover your work.

Git stash is pretty useful, but there are many other commands that you may find useful when using Git :

  • You can learn how to set the upstream branch on Git;
  • If you are just starting out, you can start by cloning repositories into your system.

If you are interested in software engineering, we have a complete section dedicated to it on the website, so make sure to check it out!

How To Unstage Files on Git | Different Ways to Unstage Files in Git

As developers, using & working with Git is mandatory. Git Users every time deals with many files in the local repository. If any user accidentally added any file to your Git then you can remove it from your index by performing the unstage files on Git. Unstaging file is very beneficial, it can be used to separate files in different commits or to do work on some other modifications.

If you are a beginner, then take help from the Junos Notes provided Git Commands Tutorial. However, this tutorial is completely on How to unstage files on Git and it addresses various methods to unstage all files or particular files or committed files elaborately in the below modules.

Prerequisites

  • Firstly, Installation of Git is the required
  • A Git project
  • Create a local and remote repository
  • A terminal window/command line
    • Linux: Activities > Search > Terminal
    • Windows: right-click Start > Command prompt (or Windows PowerShell)

Unstage a File in Git

In Git, unstaging a file can be done in two ways.

1) git rm –cached <file-name>
2) git reset Head <file-name>

1. Unstage Files using git `rm` command

One of the methods to unstage git files is using the ‘rm’ command. It can be used in two ways:

1) On the brand new file which is not on Github.
2) On the existing file which exists on Github.

Let’s check the process of using the git rm command in both scenarios.

Case 1: rm –cached on new file which is not committed.

rm –cached <brand-new-file-name> is useful to remove only the file(s) from the staging area where this file is not available on GitHub ever. After executing this command, the file rests in the local machine, it just unstaged from the staging area.

Example:

$ git add filetwo.txt
$ git status

On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: filetwo.txt

$ git rm --cached filetwo.txt
$ git status

On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
filetwo.txt
nothing added to commit but untracked files present (use "git add" to track)

Case 2: rm –cached on existing file.

If ‘rm –cached <existing-file-name>.’command is utilized on the existing file on git then this file will be considered for delete and endures as untracked on the machine. If we make a commit after this command then the file on Github will be deleted forever. We should be very careful while using this command. So, this case is not advised for unstaging a file.

Do Refer: How To Clean Up Git Branches

2. Unstage Files using git reset

The most effortless way to unstage files on Git is by using the “git reset” command and specify the file you want to unstage.

git reset <commit> -- <path>

By default, the commit parameter is optional: if you don’t specify it, it will be referring to HEAD.

What does the git reset command do?

This command will reset the index entries (the ones you added to your staging area) to their state at the specified commit (or HEAD if you didn’t specify any commits).

Also, we use the double dashes as argument disambiguation meaning that the argument that you are specifying may be related to two distinct objects: branches and directories for example.

As a quick example, let’s pretend that you added a file named “README” to your staging area, but now you want to unstage this file.

$ git status

On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   README

In order to unstage the README file, you would execute the following command

$ git reset -- README

You can now check the status of your working directory again with “git status”

$ git status

On branch master
Your branch is up to date with 'origin/master'.

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        README

nothing added to commit but untracked files present (use "git add" to track)

As you probably understood by now, the “git reset” command is doing the exact opposite of the “git add” command: it removes files from the index.

Unstage all files on Git

Previously, we have seen how you can unstage a file by specifying a path or a file to be reset.

In some cases, you may want to unstage all your files from your index.

To unstage all files also you can use the “git reset” command without specifying any files or paths.

$ git reset

Again, let’s pretend that you have created two files and one directory and that you added them to your staging area.

$ git status

On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   README
        new file:   directory/file

In order to unstage all files and directories, execute “git reset” and they will be removed from the staging area back to your working directory.

$ git reset 

$ git status

On branch master
Your branch is up to date with 'origin/master'.

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        README
        directory/

nothing added to commit but untracked files present (use "git add" to track)

Remove unstaged changes on Git

In some cases, after unstaging files from your staging area, you may want to remove them completely.

In order to remove unstaged changes, use the “git checkout” command and specify the paths to be removed.

$ git checkout -- <path>

Again, let’s say that you have one file that is currently unstaged in your working directory.

$ git status

On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   README

no changes added to commit (use "git add" and/or "git commit -a")

In order to discard changes done to this unstaged file, execute the “git checkout” command and specify the filename.

$ git checkout -- README

$ git status

On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

Alternatively, if you want to discard your entire working directory, head back to the root of your project and execute the following command.

$ git checkout -- .

$ git status

On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

Unstage Committed Files on Git

In some cases, you actually committed files to your git directory (or repository) but you want to unstage them in order to make some modifications to your commit.

Luckily for you, there’s also a command for that.

Unstage Commits Soft

To unstage commits on Git, use the “git reset” command with the “–soft” option and specify the commit hash.

$ git reset --soft <commit>

Alternatively, if you want to unstage your last commit, you can the “HEAD” notation in order to revert it easily.

$ git reset --soft HEAD~1

Using the “–soft” argument, changes are kept in your working directory and index.

As a consequence, your modifications are kept, they are just not in the Git repository anymore.

Inspecting your repository after a soft reset would give you the following output, given that you unstaged the last commit.

$ git status

On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   README

What happens if you were to hard reset your commit?

In this case, all changes would be discarded and you would lose your changes.

Unstage Commits Hard

To unstage commits on Git and discard all changes, use the “git reset” command with the “–hard” argument.

$ git reset --hard <commit>

Note: Be careful when using the reset hard command, you will lose all your changes when hard resetting.

Conclusion

In this tutorial, you learned how you can unstage files easily on Git using the “git reset” command.

You learned that you can either specify a path or a single file to unstage files and keep on working on your files until you commit them to your repository.

If you are curious about Git, we have a whole section dedicated to it on the website, make sure to have a look!

How To Switch Branch on Git

How To Switch Branch on Git | What is Git Switch? | Git Switch vs Checkout

Apparently, managing various branches in your Git Repository when working on a project is difficult. So, switching from one branch to another branch or else to the master branch should be done frequently for better performance. In Git, changing branches can be performed by checkout command whereas to switch branches in old versions.

Now, we have the Git Switch command to easily switch branches on Git also various Git Commands can support you in performing Git tasks. In this tutorial, you will learn how to switch branches on Git using Checkout & Switch command along with How do you switch between local Git branches?

What is Git Switch?

A simple alternative to ‘checkout’ is the “switch” command in git. It lets you switch your current HEAD branch. It was added newly in Git v2.23. Before the switch, the amending branches had to be done with the checkout command.

By using the checkout command you can not only use it to switch branches, but also to discard changes, restore files, and much more. Git switch has a very clear and limited purpose like switching and creating branches!

Switch Branch using git checkout

The simplest way to switch branches on Git is to use the “git checkout” command and specify the name of the branch you want to switch to.

If the destination branch does not exist, you have to append the “-b” option, otherwise, you won’t be able to switch to that branch.

$ git checkout <existing_branch>

$ git checkout -b <new_branch>

As an example, let’s say that you want to switch from the master branch to another branch named “feature” in your repository.

First, make sure that the target branch exists by running the “git branch” command.

$ git branch

Switch Branch using git checkout git-branch

Now that you made sure that your branch exists, you can switch from the master branch to the “feature” branch by executing the “git checkout” command.

$ git checkout feature

Switch Branch using git checkout git-checkout

That’s it!

You have successfully switched to your “feature” branch with the checkout command.

Do Check: How To Create a Git Branch

How to switch to a non-existing branch in Git?

On the other hand, if you try to switch to a non-existing branch, you will the following error message

$ git checkout non-existing-branch

error: pathspec 'non-existing-branch' did not match any file(s) known to git

To solve this error, you will have to append the “-b” (for “new branch”) option to the checkout command.

$ git checkout -b non-existing-branch

Switched to a new branch 'non-existing'

Now that you know more about the “checkout” command, let’s see another useful command to change branches using Git.

Switch branch using git switch

A quick way of switching branches on Git is to use the “git switch” command and specify the name of the branch you want to switch to.

If the destination branch does not exist, you have to specify the “-c” option (for “create branch“), otherwise, you will get an error message when switching to that branch.

$ git switch <existing_branch>

$ git switch -c <non_existing_branch>

Again, as an example, let’s say that you want to switch to the “feature” branch from the “master” branch.

In order to switch from the “master” branch to the “feature” branch, use the “git switch” command and specify the destination branch (which is “feature” in this case)

$ git switch feature

Switch Branch using git checkout git-checkout

On the other hand, if you try to switch to a nonexisting branch, you will get the following error message

$ git switch non-existing-branch

fatal: invalid reference: non-existing-branch

To solve this error, make sure to append the “-c” option to the “git switch” command to specify that you want to switch to a new branch.

$ git switch -c non-existing-branch

Switched to a new branch 'non-existing-branch'

Congratulations, you have now successfully switched to another branch and you can start working on it.

How do you switch between local Git branches?

First, you need to begin with running the git branch command to view a list of your local branches so that you understand which branches you have to work with and which branch you currently have checked out.

Later, you will utilize the git checkout command to checkout, or switch to, a different local branch. It should look something like this:

$ git checkout <name-of-branch-you-want-to-switch-to>

Checkout Remote Branch on Git

In some cases, you may be interested in checking out remote branches from your distant repository.

In order to switch to a remote branch, make sure to fetch your remote branch with “git fetch” first. You can then switch to it by executing “git checkout” with the “-t” option and the name of the branch.

$ git fetch

$ git checkout -t <remote_name>/<branch_name>

The “-t” option in checkout stands for “track” and it is used to create your branch and setting up the upstream branch automatically to the remote branch.

As an example, let’s say that you have a branch named “remote-branch” on the “origin” remote.

In order to check out the remote branch, you will need to execute the checkout command and specify the information specified above.

$ git checkout -t origin/remote-branch

Branch 'remote-branch' set up to track remote branch 'remote-branch' from 'origin'.
Switched to a new branch 'remote-branch'

As you can see, the remote tracking information was set automatically: as a consequence, if you commit any modifications, you will automatically push them to the upstream branch.

Checkout New Branch from Specific Commit

In some cases, you may need to switch to a new branch, but you want it to start from a specific commit on the branch.

In order to checkout a new branch from a specific start point, you have to execute the “git checkout” command and specify the “-B” option, as well as the branch and its start point.

$ git checkout -B <branch> <start_point>

In order to checkout to a specific start point, you will have to list the commits done in your repository using the “git log” command.

$ git log --oneline --graph

* 98a14be Version 2 commit (master, HEAD)
* 53a7dcf Version 1.0 commit
* 0a9e448 added files
* bd6903f first commit

As you can see, the HEAD of the master branch is at 98a14be but we want to checkout to the commit just before HEAD (which is 53a7dcf).

In order to switch to the master branch, on this specific commit, we are going to execute the “git checkout” command and specify the “master” branch as well as the commit SHA.

$ git checkout -B master 53a7dcf 

Switched to and reset branch 'master'

In order to check that you are correct on a specific commit, you can use the “git log” command again.

$ git log --oneline --graph

Checkout New Branch from Specific Commit git-log

Awesome, you have successfully switched to another branch on a specific commit.

Conclusion

In this tutorial, you learned how you can easily switch to a branch on Git using the checkout command or the switch command.

You also learned that you can switch to a branch that does not exist yet by specifying the “-b” option or the “-c” option.

Finally, you have discovered advanced tips related to switching branches: checking out a remote branch and checking out a branch from a specific starting point.