How To Undo Last Git Commit

How To Undo Last Git Commit | Process of Undoing the Last Commit in Git

At some times when you are working with Git, it happens to undo some commits like the last commit from your repository because of changes performed by you at the time of issuing the commit. In order to undo the last commit from your Git Repository, we have compiled many ways in this tutorial. This tutorial will easily help you undo the last commit in git using a few git commands like revert, checkout, reset, etc.

How do you see the last commit?

To test a specific commit, you need the hash. To get the hash you can run git log, then you can notice this output:

root@debian:/home/debian/test-project# git log
commit <last commit hash>
Author: Isabel Costa <example@email.com>
Date: Sun Feb 4 21:57:40 2018 +0000

<commit message>

commit <before last commit hash>
Author: Isabel Costa <example@email.com>
Date: Sun Feb 4 21:42:26 2018 +0000

<commit message>

(...)

You can also run git log –oneline to explain the output:

root@debian:/home/debian/test-project# git log --oneline
<last commit hash> <commit message>
cdb76bf Added another feature
d425161 Added one feature

(...)

To test a specific commit (e.g.: <before last commit hash>), that you think has the last working version, you can type the following command:

git checkout <commit hash>

This will make the working repository match the state of this exact commit.

Once you are done with this command, you’ll get the following output:

root@debian:/home/debian/test-project# git checkout <commit hash>
Note: checking out '<commit hash>'.

You are in a 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you to create, you may do so (now or later) by using -b with the checkout command again. Example:

git checkout -b new_branch_name

HEAD is now at <commit hash>... <commit message>

After examining the particular commit, if you then decide to stay in that commit state, you can undo the last commit.

Undo Last Git Commit with reset

The easiest way to undo the last Git commit is to execute the “git reset” command with the “–soft” option that will preserve changes done to your files. You have to specify the commit to undo which is “HEAD~1” in this case.

The last commit will be removed from your Git history.

$ git reset --soft HEAD~1

If you are not familiar with this notation, “HEAD~1” means that you want to reset the HEAD (the last commit) to one commit before in the log history.

$ git log --oneline

3fad532  Last commit   (HEAD)
3bnaj03  Commit before HEAD   (HEAD~1)
vcn3ed5  Two commits before HEAD   (HEAD~2)

So what is the impact of this command?

The “git reset” command can be seen as the opposite of the “git add” command, essentially adding files to the Git index.

When specifying the “–soft” option, Git is instructed not to modify the files in the working directory or in the index at all.

As an example, let’s say that you have added two files in your most recent commit but you want to perform some modifications on this file.

$ git log --oneline --graph

* b734307 (HEAD -> master) Added a new file named "file1"
* 90f8bb1 Second commit
* 7083e29 Initial repository commit

As a consequence, you will use “git reset” with the “–soft” option in order to undo the last commit and perform additional modifications.

$ git reset --soft HEAD~1

$ git status

On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   file1

$ git log --oneline --graph

* 90f8bb1 (HEAD -> master) Second commit
* 7083e29 Initial repository commit

As you can see, by undoing the last commit, the file is still in the index (changes to be committed) but the commit was removed.

Awesome, you have successfully undone the last Git commit on your repository.

Hard Reset Git commit

In the previous section, we have seen how you can easily undo the last commit by preserving the changes done to the files in the index.

In some cases, you simply want to get rid of the commit and the changes done to the files.

This is the purpose of the “–hard” option.

In order to undo the last commit and discard all changes in the working directory and index, execute the “git reset” command with the “–hard” option and specify the commit before HEAD (“HEAD~1”).

$ git reset --hard HEAD~1

Be careful when using “–hard”: changes will be removed from the working directory and from the index, you will lose all modifications.

Back to the example, we have detailed before, let’s say that you have committed a new file to your Git repository named “file1”.

$ git log --oneline --graph

* b734307 (HEAD -> master) Added a new file named "file1"
* 90f8bb1 Second commit
* 7083e29 Initial repository commit

Now, let’s pretend that you want to undo the last commit and discard all modifications.

$ git reset --hard HEAD~1

HEAD is now at 90f8bb1 Second commit

Great, let’s now see the state of our Git repository.

$ git status

On branch master
Your branch is up to date with origin/master
  (use "git push" to publish your local commits)

nothing to commit, working tree clean

As you can see, the file was completely removed from the Git repository (index + working directory)

Mixed reset Git commit

In order to undo the last Git commit, keep changes in the working directory but NOT in the index, you have to use the “git reset” command with the “–mixed” option. Next to this command, simply append “HEAD~1” for the last commit.

$ git reset --mixed HEAD~1

As an example, let’s say that we have added a file named “file1” in a commit that we need to undo.

$ git log --oneline --graph

* b734307 (HEAD -> master) Added a new file named "file1"
* 90f8bb1 Second commit
* 7083e29 Initial repository commit

To undo the last commit, we simply execute the “git reset” command with the “–mixed” option.

$ git reset --mixed HEAD~1

When specifying the “–mixed” option, the file will be removed from the Git index but not from the working directory.

As a consequence, the “–mixed” is a “mix” between the soft and the hard reset, hence its name.

$ git status

On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

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

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

Great! You found another way to revert the last commit while preserving changes done to files.

In the next section, we are going to see another way to revert the last commit using the git revert command.

Undo Last Commit with revert

In order to revert the last Git commit, use the “git revert” and specify the commit to be reverted which is “HEAD” for the last commit of your history.

$ git revert HEAD

The “git revert” command is slightly different from the “git reset” command because it will record a new commit with the changes introduced by reverting the last commit.

Note also that with “git reset” you specified “HEAD~1” because the reset command sets a new HEAD position while reverting actually reverts the commit specified.

As a consequence, you will have to commit the changes again for the files to be reverted and for the commit to be undone.

As a consequence, let’s say that you have committed a new file to your Git repository but you want to revert this commit.

$ git log --oneline --graph

* b734307 (HEAD -> master) Added a new file named "file1"
* 90f8bb1 Second commit
* 7083e29 Initial repository commit

When executing the “git revert” command, Git will automatically open your text editor in order to commit the changes.

Undo Last Commit with revert undo-2

When you are done with the commit message, a message will be displayed with the new commit hash.

[master 2d40a2c] Revert "Added a new file named file1"
 1 file changed, 1 deletion(-)
 delete mode 100644 file1

Now if you were to inspect your Git history again, you would notice that a new commit was added in order to undo the last commit from your repository.

$ git log --oneline --graph

* 2d40a2c (HEAD -> master) Revert "Added a new file named file1"
* 1fa26e9 Added a new file named file1
* ee8b133 Second commit
* a3bdedf Initial commit

How to undo a commit with git checkout

With the help of the git checkout command, we can check out the previous commit, putting the repository in a state before the crazy commit occurred. Checking out a particular commit will set the repo in a “detached HEAD” state. This implies you are no longer working on any branch. In a detached state, any new commits you make will be orphaned when you change branches back to an established branch.

Orphaned commits are up for deletion by Git’s garbage collector. The garbage collector works on a configured interval and forever ruins orphaned commits. To stop orphaned commits from being garbage collected, we have to assure we are on a branch.

From the detached HEAD state, we can perform git checkout -b new_branch_without_crazy_commit. This will create a new branch named new_branch_without_crazy_commit and switch to that state. The repo is now on a new history timeline in which the 872fa7e commit no longer exists.

At this point, we can continue work on this new branch in which the 872fa7e commit no longer exists and consider it ‘undone’. Unfortunately, if you require the previous branch, maybe it was your main branch, this undo strategy is not relevant. Let’s look at some other ‘undo’ strategies.

Conclusion

In this tutorial, you have seen all the ways of undoing the last commit of your Git repository. Also, learnt about the “git reset” command and the different ways of executing it depending on what you want to keep or not.

Moreover, you have discovered the difference between the git reset and the git revert command, the latter adding a new commit in order to revert the one from your repository.

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

If you like Git, you might like our other articles :

How To Amend Git Commit Message

How To Amend Git Commit Message | Change Git Commit Message After Push

If you are experienced with Git, then you should aware of how important to create commits for your project. If a commit message includes unclear, incorrect, or sensitive information, you can amend it locally and push a new commit with a new message to GitHub.

In this tutorial, we are going to talk completely about how to Amend Git Commit Message easily. As it can be possible in multiple different cases, also by using various suitable Git commands so make sure to pick the one who suits your needs the most.

You can also check Google Sheets Tips – New Google Spreadsheet Hacks, Tricks with Examples

The Git Commit Amend Command

This command will allow you to change files in your last commit or your commit message. Your old commit is replaced with a new commit that has its own ID.

The following syntax is for the amend command:

git commit --amend

Amending a commit does not simply change a commit. It substitutes it with a new commit which will have its own ID.

Commit has not been pushed online

In case the commit only exists in your local repository which has not been pushed to GitHub, you can amend the commit message with the git commit --amendcommand:

  • Navigate to the repository that includes the commit you need to amend on the command line.
  • Type git commit --amend and click on Enter
  • Later, Edit the commit message and save the commit in your text editor.
    • You can add a co-author by adding a trailer to the commit.
    • You can create commits on behalf of your organization by adding a trailer to the commit.

The new commit and message will seem on GitHub the next time you push.

Also Check: How To Undo Last Git Commit

How to Amend the latest Git Commit Message?

Are you looking for the process of amending the latest Git commit message?  This section will explain you clearly. In case the message to be amended is for the latest commit to the repository, then the following commands are to be performed:

git commit --amend -m "New message"
git push --force repository-name branch-name

Remember that using –force is not supported, as this changes the history of your repository. If you force push, people who have already cloned your repository will have to manually fix their local history.

Amend Older or Multiple Git Commit Message using rebase

The easiest way to amend a Git commit message is to use the “git rebase” command with the “-i” option and the SHA of the commit before the one to be amended.

You can also choose to amend a commit message based on its position compared to HEAD.

$ git rebase -i <sha_commit>

$ git rebase -i HEAD~1  (to amend the top commit)

$ git rebase -i HEAD~2  (to amend one commit before HEAD)

As an example, let’s say that you have a commit in your history that you want to amend.

The first thing you would have to do is to identify the SHA of the commit to be amended

$ git log --oneline --graph

7a9ad7f version 2 commit
98a14be Version 2 commit
53a7dcf Version 1.0 commit
0a9e448 added files
bd6903f first commit

In this case, we want to modify the message for the second commit, located right after the first commit of the repository.

Note: In Git, you don’t need to specify the complete SHA for a commit, Git is smart enough to find the commit based on a small version of it.

First, run the “git rebase” command and make sure to specify the SHA for the commit located right before the one to be amended.

In this case, this is the first commit of the repository, having an SHA of bd6903f

$ git rebase -i bd6903f

From there, you should be presented with an interactive window showing the different commits of your history.

Amend Git Commit Message using rebase rebase

As you can see, every line is prefixed with the keyword “pick”.

Identify the commit to be modified and replace the pick keyword with the “reword” keyword.

Amend Git Commit Message using rebase reword

Save the file and exit the current editor: by writing the “reword” option, a new editor will open for you to rename the commit message of the commit selected.

Write an insightful and descriptive commit message and save your changes again.

How To Amend Git Commit Message new-commit-message

Save your changes again and your Git commit message should now be amended locally.

$ git log --oneline --graph

* 0a658ea version 2 commit
* 0085d37 Version 2 commit
* 40630e3 Version 1.0 commit
* 0d07197 This is a new commit message.
* bd6903f first commit

In order for the changes to be saved on the Git repository, you have to push your changes using “git push” with the “-f” option for force.

$ git push -f 
+ 7a9ad7f...0a658ea master -> master (forced update)

That’s it! You successfully amended the message of one of your Git commits in your repository.

Amend Last Git Commit Message

If you only want to amend the last Git commit message of your repository, there is a quicker way than having to rebase your Git history.

To amend the message of your last Git commit, you can simply execute the “git commit” command with the “–amend” option. You can also add the “-m” option and specify the new commit message directly.

$ git commit --amend         (will open your default editor)

$ git commit --amend -m <message>

As an example, let’s say that you want to amend the message of your last Git commit.

$ git log --oneline --graph

* 0a658ea Last commit message
* 0085d37 Version 2 commit
* 40630e3 Version 1.0 commit
* 0d07197 This is a new commit message.
* bd6903f first commit

Execute the “git commit” command and make sure to specify the “–amend” option.

$ git commit --amend

Amend Last Git Commit Message last-commit

Amend the commit message, save and exit the editor for the changes to be applied.

Amend Last Git Commit Message amending

[master f711e51] Amending the last commit of the history.
 Date: Fri Nov 29 06:33:00 2019 -0500
 1 file changed, 1 insertion(+)


$ git log --oneline --graph

* f711e51 (HEAD -> master) Amending the last commit of the history.
* 0085d37 Version 2 commit
* 40630e3 Version 1.0 commit
* 0d07197 This is a new commit message.
* bd6903f first commit

Again, you will need to push your changes to the remote in order for other developers to get your changes. You will need to specify the “force” option as you did in the first section.

$ git push --force

+ 0a658ea...f711e51 master -> master (forced update)

That’s it!

Your Git commit message should now be amended on the remote repository.

Conclusion

In this tutorial, you learned how you can easily amend a Git commit message whether it has already been pushed or not.

You learned that you can either modify the last Git commit with the “–amend” option, or you can modify older commits with the “rebase” command.

If changes were already pushed, you will have to update them using the “git push” command and the force option.

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

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 List Git Tags

How To List Git Tags | How to Check List of Tags in Git? | Process to List Local & Remote Tags in Git

In Git Repository, tags can be listed by using the Git Commands ie., ‘git tag’. Whenever you want to work with the list tags in git first make sure that the latest list from the remote repository has been fetched or not. Users require the git list tags of the repository to discover the needed commit point.

You can find different ways to obtain the list of git tags of the local and remote repository. In this tutorial, we have compiled various ways to find out the list git tags on your repository easily.

How to List All Tags in Git?

If you want to list all available tags in a project then make use of the git tag command (keep in mind that they will appear in alphabetical order):

$ git tag
v1.0
v2.0

This method of listing git tags is excellent for small projects, but bigger projects can have hundreds of tags, so you should require to filter them when searching for an important point in history. You can obtain tags including specific characters by adding an -l to the git tag command:

$ git tag -l "v2.0*"
v2.0.1
v2.0.2
v2.0.3
v2.0.4

Must View: How To Delete Local and Remote Tags on Git

List Local Git Tags

In order to list Git tags, you have to use the “git tag” command with no arguments.

$ git tag

v1.0
v2.0

You can also execute “git tag” with the “-n” option in order to have an extensive description of your tag list.

$ git tag -n

List Local Git Tags git-tag-n

Optionally, you can choose to specify a tag pattern with the “-l” option followed by the tag pattern.

$ git tag -l <pattern>

List Local Git Tags git-tag

Awesome, you have successfully listed tags on your Git repository!

List Remote Git Tags

As you already know, Git is a decentralized versioning system. As a result, you may have not fetched some tags that have been made available by other developers on your repository.

In order to list remote Git tags, you have to use the “git ls-remote” command with the “–tags” option and the name of your remote repository.

$ git ls-remote --tags <remote>

For example, if your remote name is “origin”, you will have to execute the following command.

$ git ls-remote --tags origin

53a7dcf1ca57e05d456321b406730b39dc8ed75e        refs/tags/v1.0
7a9ad7fd794bf52a11de43aacc6010978e6100d3        refs/tags/v2.0

Note: As you can see, by using the “ls-remote” command, you are presented with tags using the “refs” syntax that was already explained in our previous tutorials.

List and Sort Git Tags

Additionally, you can choose to list your tags and sort them following a lexical or a version sorting.

In order to list Git tags following a lexicographic order, you have to use the “git tag” command with the “–sort=refname” option and an additional tag pattern.

$ git tag -l --sort=refname <pattern>

List and Sort Git Tags git-tag-sort

Sorting by refname is not the only way of sorting Git tags.

You can also choose to sort your tags by versions: this way, your tag names will be treated as version numbers.

In order to list Git tags sorted by version numbers, you have to use the “git tag” command with the “–sort=version:refname” option and an additional tag pattern.

$ git tag -l --sort=-version:refname <pattern>

List and Sort Git Tags git-tag-2

Sorting most recent Git tags

In order to list and sort Git tags by their latest Git activity, you can use the “git tag” command with the “–sort=committerdate”.

$ git tag --sort=committerdate -l <pattern>

Sorting most recents Git tags committer

Congratulations, you successfully sorted your Git tags using the sort options!

Fetching Remote Tags Easily

Now that you know that some tags are available remotely, you may want to fetch your tags in order to list them locally.

To fetch tags from your remote repository, use “git fetch” with the “–all” and the “–tags” options.

$ git fetch --all --tags

Fetching origin
From git-repository
   53a7dc..7a9ad7    master     -> origin/master
 * [new tag]         v1.0       -> v1.0
 * [new tag]         v1.0       -> v2.0

Awesome, you fetched your tags from your distant repository!

Now, you can list them easily using the “git tag” command (with no arguments!)

$ git tag

v1.0
v2.0

Find Latest Git Tag Available

In order to find the latest Git tag available on your repository, you have to use the “git describe” command with the “–tags” option.

This way, you will be presented with the tag that is associated with the latest commit of your current checked-out branch.

$ git describe

<latest_tag>

Conclusion

From this tutorial, you discovered how you can easily list your Git tags, whether they are local or remote.

You also learned that you can use advanced sorting options in order to have your results sorted by recent date or version number.

We have other tutorials on Git tags, make sure to have a read:

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 Checkout Git Tags

How To Checkout Git Tags | How Do You Checkout Latest Git Tag Easily?

In Git, tags are references that point to a specific point in time and are commonly used to identify release versions of your code. When you are working with Git, it is necessary to build tags to ought reference points in their development.

Tags are utilized to mark specific commits in Git, e.g. release versions. While a branch pointer moves at additional commits are made, a tag remains set on the specified revision.

Moreover, tags are Git objects indicating that they can be checked out like you would check out a branch or a commit for instance. In this short tutorial, we will be discussing how to checkout a tag in Git easily. Along with this, you can also take a look at the checkout of the latest git tag with the help of Git Commands.

Checkout Git Tag using ‘git checkout’ command

To checkout, a Git tag, use the “git checkout” command and specify the tag name as well as the branch to be checked out.

$ git checkout tags/<tag> -b <branch>

Note that you will have to make sure that you have the latest tag list from your remote repository.

To fetch tags from your remote repository, use “git fetch” with the “–all” and the “–tags” options.

$ git fetch --all --tags

Fetching origin
From git-repository
   98a14be..7a9ad7f  master     -> origin/master
 * [new tag]         v1.0       -> v1.0

Let’s say for example that you have a tag named “v1.0” that you want to check out in a branch named “release”.

To achieve that, you would execute the following command

$ git checkout tags/v1.0 -b v1.0-branch

Switched to a new branch 'v1.0-branch'

Using this command, you have successfully checked out the “v1.0” tag.

You can inspect the state of your branch by using the “git log” command. Make sure that the HEAD pointer (the latest commit) is pointing to your annotated tag.

$ git log --oneline --graph

* 53a7dcf (HEAD -> v1.0-branch, tag: v1.0) Version 1.0 commit
* 0a9e448 added files
* bd6903f (release) first commit

Awesome!

Now you can start working on your branch starting from the tag you specified earlier.

Checkout latest Git tag

In some cases, you may be interested in checking out the latest Git tag of your repository.

To check out the latest Git tag, first, update your repository by fetching the remote tags available.

$ git fetch --tags

Fetching origin
From git-repository
   98a14be..7a9ad7f  master     -> origin/master
 * [new tag]         v2.0       -> v2.0
 * [new tag]         v1.0       -> v1.0

As you can see, you retrieve multiple tags from your remote repository.

Then, retrieve the latest tag available by using the “git describe” command.

$ tag=$(git describe --tags `git rev-list --tags --max-count=1`)

$ echo $tag
v2.0

Finally, use the “git checkout” command to checkout the latest git tag of your repository.

$ git checkout $tag -b latest

Switched to a new branch 'latest'

That’s it! You have successfully checkout the latest Git tag available in a new branch.

You can execute the “git log” command to make sure that you are actually developing starting from the new tag.

$ git log --oneline --graph

* 7a9ad7f (HEAD -> latest, tag: v2.0, origin/master, master) version 2 commit
* 98a14be Version 2 commit
* 53a7dcf (tag: v1.0, v1.0-branch) Version 1.0 commit
* 0a9e448 added files
* bd6903f (branch3) first commit

Conclusion

In this tutorial, you have seen how you can easily checkout tags on Git using the “git checkout” command. Also, we have covered the information about checking out the latest Git tags from your repository in case you have multiple tags.

Interested in Git tags? Check our guide on how to delete local and remote git tags.