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.

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 Delete File on Git

How To Delete File on Git | Removing Files from Git Repository using git rm Command

We all know how important to add many files into a git repository for developing the project. But developers should realize and work on deleting unused files on git. Always, delete files on git is so confusing as it is a big question mark to delete them from my repository or delete them from the filesystem?

Also, Have a look at the Git Commands for gaining enough knowledge & practice on Git.

To clear your confusion, we have come up with this new Git Tutorial on How to Delete File on Git. Here, we have explained completely how you can easily delete files on Git, whether it is only from your Git repository or from the filesystem. Let’s dive into it without any further do.

The git rm Command

Whenever you are planning to delete or remove a file or multiple files from a git repository, then this command ie., git rm is used. Not only it deletes but also remove files from the staging index and the working directory. If you wish then it could also delete files from the filesystem.

Deleting a file from the actual Git repository is a separate task that is done easily by the git rm command. But removing the file from the filesystem can be made in several other applications, e.g. a text editor, IDE, or file browser.

Also Check: How To Delete a GitHub Repository

Delete Files using git rm

The easiest way to delete a file in your Git repository is to execute the “git rm” command and specify the file to be deleted.

$ git rm <file>

$ git commit -m "Deleted the file from the git repository"

$ git push

Delete Files using git rm git-rm

Note that by using the “git rm” command, the file will also be deleted from the filesystem.

Also, you will have to commit your changes, “git rm” does not remove the file from the Git index unless you commit it.

As always, let’s have a quick example in order to illustrate the commands we just described.

In my current repository, I have three files named “file1”, “file2” and “file3” and I want to delete the “file1” file from my Git repository.

By using the “git ls-tree” command, I am able to see the files tracked on my current branch.

$ git ls-tree -r master

Delete Files using git rm git-list-tracked-files

In order to delete the file “file1” from the Git repository and from the filesystem, we are going to execute the “git rm” command with the name of the file.

$ git rm file1
rm 'file1'

You should get a small confirmation message saying that the “rm” command was executed on this file.

How To Delete File on Git git-rm-example

So what happened here?

As you can see, by executing the “git rm” command, a “deleted” action was added to the changes to be committed.

It means that the file was removed from the filesystem but it was not deleted from the index just yet.

In order for the changes to be effective, you will have to commit your changes and push them to your remote repository.

How To Delete File on Git git-rm-commit-changes

Now the file should be deleted from the filesystem and from the index, you can verify it by re-executing the “git ls-tree” command in order to list files in the current index.

How To Delete File on Git git-list-files-index

Congratulations, you successfully deleted a file from your Git repository.

Removing Multiple Files

Deleting multiple files from a repo is the same as the early use-case of removing a single file using git rm. On the basis of your preferred method, there are some ways to do this. For instance, you can just explicitly list all files to be deleted like below:

$ git rm lib/db.js lib/api.js
rm 'lib/api.js'
rm 'lib/db.js'

Or, if there are more files than you feel like listing, you can always use the wildcard character:

$ git rm lib/*.js
rm 'lib/api.js'
rm 'lib/db.js'

Be noted that by deleting all of the contents from the lib directory, Git will also remove the actual directory itself. This is done because Git only tracks files, not directories:

$ git ls-files
.gitignore
index.js
package.json

Delete Files Recursively on Git

In order to delete files recursively on Git, you have to use the “git rm” command with the “-r” option for recursive and specify the list of files to be deleted.

$ git rm -r <folder>

$ git commit -m "Deleted the folder from the repository"

$ git push

This is particularly handy when you need to delete an entire directory or a subset of files inside a directory.

As an example, let’s say that our Git repository has a folder named “folder1” that contains two files.

In order to delete this folder, and the files contained in it, we are going to execute the “git rm” command with the “-r” option.

$ git rm -r folder1

Delete Files Recursively on Git git-rm-recursive
Again, do not forget that the changes are effective when you commit them, not before.
Delete Files Recursively on Git git-delete-folder

Congratulations, you successfully removed an entire folder from your Git repository.

Delete Files From Git Repository Only

In some cases, you want to delete files from the Git repository but not from the filesystem, you have to execute the “git rm” command with the “–cached” option.

$ git rm --cached <file>

$ git commit -m "Deleted file from repository only"

$ git push

Back to our example, we currently have two files sitting in our working folder: file2 and file3.

Let’s pretend that we want to delete the file “file2” from the repository but we want to keep it on the filesystem.

To achieve that, we simply execute the “git rm” command with the “–cached” option.

$ git rm --cached file2

Delete Files From Git Repository only git-rm-cached

As you can see, after executing the “git rm” command, the file is still on the filesystem.

Awesome, you simply have to commit and push the changes now for them to be effective.

What’s in my git status?

Before committing your changes, you may notice with a “git status” command that the file was added to the changes to be committed, as well as in the list of untracked files.

Delete Files From Git Repository only git-status-command

Quite logic because your file is not tracked anymore as the result of your previous deletion.

Now for the file not to be listed in your Git repository under the “untracked files”, make sure to add it to your Git Ignore file.

$ touch .gitignore

# Content of the gitignore file

file2

What s in my git status gitignore-files

Commit your gitignore file and you should be good to go!

Delete Files From Git History

In some cases, you want to delete files from your entire Git history.

It may be the case for example if you committed a file that contains passwords or some sensitive information, that you want to remove.

In order to delete the file from Git history, you have to use the “git filter-branch” command and specify the command to be executed on all the branches of your Git history.

Finally, you want to specify the revision to execute the changes from we are going to choose HEAD (as a reminder, HEAD is the last commit of your repository).

In this case, the Git command to be executed is the “git rm” command we described earlier.

$ git filter-branch --force --index-filter --prune-empty "git rm --cached --ignore-unmatch <path_to_file>" HEAD

As the command is quite complex, let’s have a breakdown of all the options used :

  • –force: quite self-explanatory, it forces the filter-branch to start even if it may not want to (given the documentation because it can contain temporary directories)
  • –index-filter: option used in order to rewrite the index, exactly what we want in the case of a file deletion
  • “git rm” command: the command to be executed on all branches, revisions, and commits matching in the history, in this case, it will remove the file from the repository and ignore files that don’t match
  • –prune-empty: avoid having empty commits in the repository with zero files, this option will prune commits automatically

In this case, let’s say that we want to delete the file “file1” contained in our repository.

We are going to execute the following command.

$ git filter-branch -f --prune-empty --index-filter "git rm -r --cached --ignore-unmatch ./file1" HEAD

Delete Files From Git History rewrite-history

This command can take a while if your history contains many files, but in the end, the deleted file won’t be in your Git history anymore.

You can check with a “git log” command, but the commits linked to the deleted file should be pruned if necessary.

Conclusion

In this tutorial, you learned how you can easily delete a file from a Git repository, whether you want to delete it from the filesystem or not. Also, learned that it is completely possible to delete a file from an entire Git repository using the “filter-branch”.

Deleting files in Git is associated to file restoration, as a result, you may be interested in the following resources:

How To Git Add All Files

How To Git Add All Files | Git How to Add All Modified File to Commit?

Adding new files or a bunch of files to the repositories is quite common for all developers working on the software project with Git. In various cases, we face a situation where we need to add multiple files to git. To make it possible, Git provides a single command for that i.e. git add command also check other Git Commands from this available quick link.

In case, if you want to add untracked files to your repository then also you can simply refer & utilize the same command. Well, this tutorial is designed to explain how easily add all your files to your Git repository. Also, you can learn how to Git Add All New files, modified files, deleted files, untracked files, etc. from the available links.

Determine your Git version

Depending on the current Git version that you installed on your computer, the “git add” command can differ.

To determine your current Git version, use “git” followed by the “–version” option.

$ git --version

Determine your Git version git-version

Add All Files using Git Add

The easiest way to add all files to your Git repository is to use the “git add” command followed by the “-A” option for “all”.

$ git add -A                       

$ git add .                        (at the root of your project folder)

In this case, the new (or untracked), deleted and modified files will be added to your Git staging area. We also say that they will be staged.

Alternatively, you can use the “git add” followed by a “.” which stands for “current directory”. However, using the “.” syntax implies that you are currently at the top of your project folder hierarchy.

As an example, let’s say that we created a branch named “feature“. On this branch, we have three files: one deleted, one with its content modified, and another one that is untracked.
Add All Files using Git Add git-add-all-files

In order to add all those files to our staging area, we will use the “git add” command followed by the “-A” option.

Add All Files using Git Add adding-all-files

As you can see, the files were correctly added to the staging area, awesome!

You can now commit them to your Git repository in order for the changes to be shared with your colleagues.

The Git Add Command

This command updates the index using the current content found in the working tree, to prepare the content staged for the next commit. It typically adds the current content of existing paths as a whole, but with some options, it can also be used to add content with only part of the changes made to the working tree files applied or remove paths that do not exist in the working tree anymore.

The git add command will not add ignored files by default. If any ignored files were explicitly specified on the command line, git add will fail with a list of ignored files.

The SYNOPSIS of the git add command is as follows:

git add [--verbose | -v] [--dry-run | -n] [--force | -f] [--interactive | -i] [--patch | -p]
[--edit | -e] [--[no-]all | --[no-]ignore-removal | [--update | -u]]
[--intent-to-add | -N] [--refresh] [--ignore-errors] [--ignore-missing] [--renormalize]
[--chmod=(+|-)x] [--pathspec-from-file=<file> [--pathspec-file-nul]]
[--] [<pathspec>…​]

Adding all files by Wildcard

In some cases, you may be interested in adding all files that have a specific extension : *.txt or *.js for example.

To add all files having a specific extension, you have to use the “git add” command followed by a wildcard and the extension to add.

$ git add *.txt

$ git add *.js

As an example, let’s say that you have created two Javascript files and one text file.

Adding all files by extension add-file-by-extension

In order to add all Javascript files, we are going to use the wildcard syntax followed by “*.js”.

$ git add *.js

Adding all files by extension wildcard-git-add

Congratulations, you successfully added your files having a specific extension!

Using dot with git add

As explained before, the “.” symbol stands for “current directory“.

As a consequence, if you don’t use it at the top of your project hierarchy, you will only add files in the current working directory.

To illustrate this concept, let’s say that you have two new files: “root-file” in your project top folder and “new-file” in a folder named “folder”.

Using dot with git add git-add-dot

If you navigate to your new folder and execute the “git add” command with the dot syntax, you will notice that you only add files located in this directory.

$ cd folder

$ git add .

Using dot with git add git-add-dot-syntax

As a consequence, you might miss some of your files in your commit.

To avoid this problem, you can use the dot syntax combined with the absolute path to your project top folder.

$ git add <path>/.

Using dot with git add git-add-absolute-path

Adding all files on older Git versions

In the first chapter, we use the “–version” option in order to check our current Git version.

This step is quite important because the behaviour of the “git add” command can differ depending on the Git version used.

If you use the dot syntax with an old Git version (less than 2.x), the modified and deleted files won’t be automatically added to your commit.

Adding all files on older Git versions git-add-chart

Adding All deleted and modified files

In order to add all deleted and modified files only to your staging area, you have to use the “git add” command followed by the “-u” option.

$ git add -u

As an example, let’s say that we modified one of our files, deleted one, and added one to our working directory.

Using a simple “git status” command, we can inspect the state of our Git working directory.

Adding deleted and modified files only git-add-deleted-files

In order to add the deleted and modified files only, we are going to execute “git add” with the “-u” option.

$ git add -u .

Adding deleted and modified files only git-status

Awesome, you successfully added all your deleted and modified files to your current Git repository!

Conclusion

In this tutorial, you learned how you can easily add all your files to your Git repository using the “git add” command. You also learned that you can use specific wildcards or options in order to add only deleted or modified files.

How To Cherry Pick Git Commits

How To Cherry Pick Git Commits | When & How to use a Git Cherry Pick Commit?

If you are working with Git, you may require to add some specific changes to your current branch. For instance, if you require to include a particular commit located on another branch than your current branch,. To perform this case make use of the required git commands ie., git cherry pick. 

It is one of the most useful commands in Git and also it does not change your current Git history rather it adds commits to it. In this tutorial, we will be explaining more about Git Cherry Pick commit and how you can use the Git cherry-pick command for including specific changes to your current branch.

Git Cherry-pick

Git cherry-picking refers to applying some commit from one branch into another branch. If you did any error and performed a change into the wrong branch, then you shouldn’t merge the whole branch. You can revert the commit and apply it to another branch.

git cherry pick commit

The principal objective of a cherry-pick is to apply the changes proposed by some current commit. Cherry-pick is a helpful tool, but always it is not a good option. It is in contrast with different ways such as merge and rebase command.

Do Refer: How To Clear Git Cache

How to use git cherry-pick?

If you want to allow the “cherry-pick” only the commits you want from another branch then Git’s cherry-pick command is useful for you. The following steps are very important to understand how to use git cheery pick:

  • Pull down the branch locally. Use your git GUI or pull it down on the command line, whatever you’d like.
  • Get back into the branch you’re merging into. You’ll likely do this by running git checkout master.
  • Find the commits you want to pull into your branch. Go to either the git log or the GitHub UI and grab the unique commit hashes for each of the commits that you want.
  • “Cherry pick” the commits you want into this branch. Run this command: git cherry-pick super-long-hash-here. That will pull just this commit into your current branch.
  • Push up this branch like normal. git push origin master

How do I cherry pick a commit in Git?

In Git, the cherry pick command drives changes from a target commit and puts them on the HEAD of the currently checked out branch.

From here, you can either continue working with these changes in your working directory or you can directly commit the changes onto the new branch.

how do i cherry pick a commit in Git

How to Cherry Pick a Commit?

Cherry-pick using Git commit hash

The easiest way to cherry-pick a commit is to use the “cherry-pick” command with the commit hash.

$ git cherry-pick <hash>

In order to cherry-pick changes, you will need to identify your commit hashes.

In order to see the commit hashes for your current branch, simply run the “git log” command with the “–oneline” option in order to make it more readable.

$ git log --oneline

45ab1a8 (HEAD -> branch2) added gitignore
808b598 (branch) Initial commit

By default, the log command will display the commits from the history beginning until the top of your current branch.

As a consequence, you may not see commits that are not related to your current branch timeline.

If you want to see commits related to a specific branch, specify the branch name when running the “git log” command.

$ git log --oneline master

93ae442 (master) committed changes
44ee0d4 added gitignore
808b598 (branch) Initial commit

As you can see, one additional commit was displayed: you can now use this hash in order to cherry-pick your commit.

$ git cherry-pick 93ae442 

[master 299a73d] added file
 Date: Wed Nov 20 16:04:52 2019 -0500
 1 file changed, 1 insertion(+)
 create mode 100644 file.txt

Great!

You have successfully cherry-picked your commit.

Cherry-pick from another branch

In order to pick commits from another branch, you need to list commits that were performed on this other branch using the “git log” command.

$ git log --oneline <branch>

Let’s say for example that I want to cherry-pick a commit from the feature branch.

$ git log --oneline feature

93ae442 (master) Feature 1
44ee0d4 Feature 2
808b598 (branch) Initial commit

Now, you can go to the branch where you want the commit to be cherry-picked, let’s call it “master” in this case.

$ git checkout master

$ git cherry-pick 93ae442 

[master 299a73d] added file
 Date: Wed Nov 20 16:04:52 2019 -0500
 1 file changed, 1 insertion(+)
 create mode 100644 file.txt

Great!

You successfully cherry-picked commits from another branch into your main branch.

Cherry-pick multiple Git commits

In some cases, you may want to cherry-pick multiple commits at once.

Luckily for you, this option is available since Git 1.7.2.

Since Git 1.7.2, you can cherry-pick a range of commits by using the dot notation.

$ git cherry-pick A..B

Note that using this command, commit A will NOT be included in the cherry-pick.

In order to include commit A, you can use this syntax

$ git cherry-pick A^..B

For example, back to the “master” branch, let’s try to cherry-pick two commits into the feature branch.

$ git checkout master

$ git log --oneline feature
481981f (feature) file 4
6653c90 file3

$ git cherry-pick 6653c90^..481981f

[master 04fbbcf] file3
 Date: Wed Nov 20 16:20:23 2019 -0500
 1 file changed, 1 insertion(+)
 create mode 100644 file3
[master f3ecc5a] file 4
 Date: Wed Nov 20 16:20:36 2019 -0500
 1 file changed, 1 insertion(+)
 create mode 100644 file4

Note that the commits need to be placed into the correct order: commit A needs to be older than commit B otherwise the command will fail silently.

Cherry-pick with original commit reference

In some cases, you may want to keep a reference to the original commit when performing a cherry-pick.

When you are performing a regular cherry-pick, you will get a new commit hash but the commit message will be the same.

However, there is a way to append the origin of a cherry-pick to the commit message: by using the cherry-pick with the “-x” option.

$ git cherry-pick -x <commit>

For example, let’s say that I cherry-picked one commit from the master branch into my “branch2” branch.

$ git cherry-pick -x ed5d4c4

Now when inspecting the commit list, you can pay attention to the commit name.

$ git log

commit de05030c3c03def40c8fa8f23e5283a7b2eaab6a (HEAD -> master)
Author: Antoine <test@gmail.com>
Date:   Wed Nov 20 16:06:10 2019 -0500

    added file 2

    (cherry picked from commit ed5d4c45dda6a6671df7d8bfc63e293ef1de23fa)

As you can see, the commit has the original commit message but it also has an informational message from the original commit

$ (cherry picked from commit <hash>)

This option can be quite handy when you want to track cherry picks done on the branch.

If you don’t specify the “-x”, you won’t be able to tell if the commit was cherry-picked in the past.

Change commit message when cherry-picking

Cherry-picking commits is very useful in order to reuse some existing work.

However, in some branches, the commit may be useful for different reasons.

As a consequence, you may want to change the commit message when cherry-picking.

To change the commit message when cherry-picking, use “git cherry-pick” with the “-e” option.

$ git cherry-pick -e <hash>

As illustrated in this example, your default editor will open and it will let you change the commit message.

Change commit message when cherry-picking own-message

When you are satisfied with the edits, save your file and your commit message should be saved successfully.

[master 1aac0e2] file5
 Date: Wed Nov 20 16:25:17 2019 -0500
 1 file changed, 1 insertion(+)
 create mode 100644 file5

Resolving cherry-pick conflicts

In some cases, you may run into cherry-pick conflicts when trying to cherry-pick your commits with the current branch.

$ git cherry-pick 93ae442

error: could not apply 93ae442... committed changes
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

This error is happening because Git is trying to merge the content of the cherry-picked commit with your current branch.

However, as in a merge operation, the content merging can fail and you will have to solve the conflicts by yourself.

In order to fix the issues, first, take a look at the status of your working directory and staging area.

$ git status

On branch branch2

You are currently cherry-picking commit 93ae442.
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Changes to be committed:

        new file:   index.js
        new file:   script.js

Unmerged paths:
  (use "git add <file>..." to mark resolution)

        both modified:   .gitignore

As you can see, the status command states that “you are currently cherry-picking commit 93ae442“.

The files to be solved are located in the “unmerged paths” section. In order to solve the cherry-pick conflict, edit the file and modify the file until you are satisfied with the modifications.

$ nano .gitignore

(Previous content)

<<<<<<< HEAD
=======
*.conf
>>>>>>> 93ae442... committed changes

(After conflict modification)

*.conf

When conflicts are solved, add the files to your staging area and continue the cherry-pick process.

$ git add .

$ git cherry-pick --continue

The last command will open your current editor in order to add a message to your current operation.

Resolving cherry-pick conflicts continue

When you are done, save your changes and your changes should be merged.

[branch2 bd8763f] Fixed conflicts on cherry-pick
 Date: Wed Nov 20 12:56:50 2019 -0500
 3 files changed, 1 insertion(+)
 create mode 100644 index.js
 create mode 100644 script.js

Great! You successfully resolved cherry pick conflicts on your current branch.

Conclusion

In this tutorial, you learned more about the git cherry-pick command and how it can be used in many ways to merge specific commits into your current working branch.

How To Git Commit With Message

How To Git Commit With Message | Best Practices & Rules To Write Good Commit Messages in Git

Using Git as a version control system for your projects is very helpful for developers. After performing any changes, you would probably need to add your files to the index and commit them to be saved. While working with Git, it will be always a good practice to create Git commits with a message.

Git commit messages are important to express and distribute with others what you did. Also, it can be helpful when working to hotfix issues appearing on your master branches. In this short tutorial, We will be discussing more on how easily one can create Git commits with messages along with best practices of Git commit messages, other Git Commands used to commit messages to learn and write good ones when required.

What is a commit message?

The usage of the commit command is for saving changes to a local repository after staging in Git. But, before you can save changes in Git, you have to tell Git which changes you want to save as you might have made tons of edits. An excellent way to do that is by adding a commit message to recognize your changes.

Git Commit With Message

The easiest way to create a Git commit with a message is to execute “git commit” with the “-m” option followed by your commit message.

$ git commit -m "Describe your commit here"

When using the Git CLI, note that you should restrict your commit message in order for it not to be wrapped.

Usually, a good practice is to keep Git commit messages under 50 characters or less.

If you want to append a description to your Git commit, you will have to use another method.

Also Check: How To Amend Git Commit Message 

Git Commit With Description

In some cases, you may want to create a Git commit with a larger description.

Furthermore, you want to make your Git commit message fit the character limit on Git.

To create a Git commit message with a large description, you have to execute the “git commit” command without any options.

On Linux or in the Git bash, it will open an editor for you to write your Git commit message.

$ git commit

When leaving the editor and creating your Git commit message, you will be able to see that the short message was taken into account to create the commit.

Git Commit With Description git-commit-2

Similarly, if you try to inspect your Git history, you will be able to see that only the short message is visible to other users.

$ git log --oneline --graph

Git Commit With Description changes
Now that you know the basics of creating Git commit messages, we will see what rules you can use in order to write proper commit messages.

Writing Good Git Commit Messages

Writing good commit messages is crucial to any workflow. Git commits provide insights on the performed work.

As a result, if they are not written properly, you have the risk of not identifying clearly what you have worked on, or what others have worked on.

This can lead to a very messy process where you are not able to perform code integration or reverse-engineer what you did in the past.

Best Practices of Git Commit Messages

Best Practices of Git Commit Messages

Five Rules To Write Great Git Commit Message

Here is a small list of rules that you can follow to write good Git commit messages:

1 – Keep your Git commit messages short and informative

When you are working on a task, you should be able to clearly identify what you are working on.

There is no such task as “creating a website” or “refactoring the entire codebase”.

# Bad habit

$ Created pages for the website

# Good habit

$ Created the sign-up form front-end and added controls

$ Added the Login button to the Login page

Instead, if you divided your big tasks from the beginning, you should have a small set of features that you can work on.

Your Git commit message should reflect the properly divided work you are currently performing.

2 – Git commit messages should reflect your Git flow

When working with Git, choosing a Git flow is essential to ensure that integrations are performed without any regression or additional bugs.

If you are not sure about Git Flow, Atlassian wrote a very useful guide about it : you should read it and choose a Git flow if not done already.

Now that your Git flow is chosen, you can reflect it in your Git commit messages.

For example, if you are working on a feature branch, you can easily write a prefix or a suffix describing the branch you are working on.

$ (on <branch>) Fixed the UI bug when creating a new user

$ Fixed the UI bug when creating a new user (on <branch>)

Note: Whenever you are trying to inspect changes done in the past, you will be able to easily identify all the branches associated with a feature.

3 – You are not working alone

Most of the time, you are not working alone on your project: you are working with other developers.

As an outcome, writing good Git commit messages is also a sign that you care about other developers on your team.

When other developers will pull your changes, they will most likely try to understand what you have done.

It is also very likely that your modifications had some kind of impact on other parts of the code that you are not directly aware of.

Being descriptive is the best way to ease the future work that they will have to do.

It might not make a big difference on one or two commits, but the impact is huge when done over several hundred commits.

# Bad habit

$ Fixed bug on code

# Good habit

$ Fixed the NullPointerException when trying to create a user from login

4 – Use good spelling and syntax for your Git commits

This is a very obvious step but you should try to keep good spelling a proper grammar when writing Git commit messages.

Also, the syntax should be adapted to the Git commit message: avoid exclamation marks and words that add nothing descriptive or useful to the content of your Git message.

# Bad habit

$ Finally fixed the UI page! 😊

# Good habit

$ Fixed the UI page by adding an try-catch clause

Usually, Git commit messages should stay neutral and they should only try to convey the intent of the commit.

5 – Use verbs that fit the modifications done

When creating Git commit messages, one of the hardest parts is coming up with verbs that describe the actions performed in the commit.

Did you fix a bug? Did you refactor a class? Did you delete some methods?

# Bad habit

$ Wrote some new code for the feature

# Good habit

$ Added unit-tests to cover the user creation workflow

Choosing the best verbs is actually crucial: there is an actual difference between fixing a bug and hot-fixing a bug for example.

One can be done on one of your feature branches while the other implies that you have performed a modification directly on one of your production branches.

Conclusion

In this tutorial, you learned how you can write good Git commits with messages.

You saw that it is possible to keep Git commit messages while adding a longer description to your commit.

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 Generate Git SSH Keys

How To Generate Git SSH Keys | Process of Git Generate SSH Key on Windows, Linux, Mac

In case you are a great expert in working with Git, then you would know that how necessary is to set up SSH authentication. Are you excited to learn how to generate Git SSH key and SSH authentication? Then, this tutorial is the best option for you.

From here, you will understand that SSH authentication is one of two ways of logging into your Git remote repository and pushing modifications to it. In this tutorial, we are explaining more about how you can generate SSH keys for Git on Linux, or on Windows, or on Mac. Along with that, you should have some knowledge of Git Commands to check the Git installation version using the command line.

Note: If you are using Github, follow this tutorial to setup SSH keys on Github

What is an SSH KEY?

The definition of an SSH key is an access credential for the SSH (secure shell) network protocol. For remote communication between machines on an unsecured open network, we use this authenticated and encrypted secure network protocol. Also, SSH is utilized for remote file transfer, network management, and remote operating system access. The SSH acronym is also utilized to specify a set of tools used to communicate with the SSH protocol.

How to Create an SSH Key?

SSH keys are created using a key generation tool. The generation of SSH keys can be through a public key cryptographic algorithm, the most common being RSA or DSA. At a very high-level SSH keys are created via a mathematical formula that uses 2 prime numbers and a random seed variable to output the public and private keys. This is a one-way formula that assures the public key can be obtained from the private key but the private key cannot be obtained from the public key.

Checking PC’s SSH Keys

You can check your PC’s SSH Keys by following the command below.

ls -al ~/.ssh

By typing the above command, you can see your SSH keys easily. The filename of the public key is one of the following by default:

id_ecdsa.pub
id_ed25519.pub
id_rsa.pub

Generate a new SSH key

If you don’t have an SSH key, first, you should create it. Later, please follow the step-by-step guide on how to generate a new SSH key.

Type the command below, using your GitHub’s account email:

ssh-keygen -t rsa -b 4096 -C "[your github's email]"

After running this command, you will be offered to set the SSH key path, but we advise you to use its default value by pressing the “Enter” button.

Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]

After that, it will allow you to insert a passphrase to protect your SSH key.

> Enter passphrase (empty for no passphrase): [Type a passphrase]
> Enter same passphrase again: [Type passphrase again]

Read More on Git: 

How to Generate SSH keys for Git authorization

This tutorial is all about generating SSK Keys on various platforms like Windows, Mac, Linux, etc. If you poor at this concept then check out how to do it by following the steps given here:

Generate SSH Keys on Linux

In order to generate SSH keys for your Git repository, use the “ssh-keygen” command and specify the encryption algorithm that you want to use.

$ ssh-keygen -t rsa -b 4096 -C "email@example.com"

Note that it is recommended to generate your SSH keys in the “.ssh” directory of your home directory.

When using the ssh-keygen utility, you will be prompted with multiple questions.

First, you will be asked to provide the filename for your key as well as the passphrase.

For the filename, you usually want to leave the default options and simply press Enter.

For the passphrase, we won’t bother choosing a passphrase for this tutorial.

Even if it includes an extra layer of security for your Git repository, you will be prompted with the passphrase every time that you want to perform an operation on the repository.

Generate SSH Keys on Linux ssh-keygen

The ssh-keygen utility created two files for you :

  • id_rsa: this is the private key of your SSH key pair, you should not share this key with anybody.
  • id_rsa.pub: this is the public key of your SSH key pair, this is the key that you will copy to your server in order to connect to it seamlessly.

Generate Git SSH Keys on Mac

Just take a look at the below provided five main steps and follow them carefully to generate SSH keys for git:

  1. Start the terminal
  2. Navigate to your home directory by typing: cd ~/
  3. Now, perform the following command: ssh-keygen -t rsa (when prompted, enter a password, the key name can stay the same)
  4. Open the file you’ve just created ~/.ssh/id_rsa.pub with your favorite text editor, and copy contents to your Git repository’s keys field (GitHub, beanstalk, or any other repository provider), under your account.
  5. Make sure that you don’t copy any whitespace while copying the public key’s content (id_rsa.pub).

Generate SSH keys for Git on Windows

In order to generate SSH keys for Git on Windows, you have to enable the OpenSSH commands using the “Add-WindowsCapability” command.

$ Add-WindowsCapability -Online -Name OpenSSH.Client*

Path          :
Online        : True
RestartNeeded : False

Note: You have to be an administrator to enable OpenSSH on your computer.

Now that OpenSSH is enabled and configured on Windows, simply use the “ssh-keygen” command in order to generate your SSH keys.

$ ssh-keygen -t rsa -b 4096 -C "email@example.com"

By default, you will be prompted to provide a public key filename as well as a passphrase.

You can leave those options empty: by default, your key-pair will be named “id_rsa” (or “id_rsa.pub” for the public key).

When it comes to the passphrase, it provides more security to add one but you will be asked to provide it on every SSH authentication.

Generate SSH keys for Git on Windows rsa-windows

As you can see, your SSH keys for Git are located in the “.ssh” directory of your user home.

The ssh-keygen utility created two files for you :

  • id_rsa: this is the private key of your SSH key pair, you should not share this key with anybody.
  • id_rsa.pub: this is the public key of your SSH key pair, this is the key that you will copy to your server in order to connect to it seamlessly.

Setup SSH authentication on Git

Now that your SSH keys are generated for Git, it is time to add them to your remote Git repository in order to push changes.

In order to setup SSH authentication on the server, you will have to copy the content of the public key to the “authorized_keys” file of the server.

Copy SSH keys to your Git server

On the client, use the “cat” command in order to see the content of the public key.

$ cat ~/.ssh/id_rsa.pub

Copy SSH keys to your Git server id-rsa

Copy the output of your cat command, and paste it into the “authorized_keys” file of your server (or remote repository).

$ sudo vi /home/git/.ssh/authorized_keys

Copy SSH keys to your Git server server

Alternatively, if you don’t want to copy and paste the content of your public key, you can use the “ssh-copy-id” command.

This command will simply take the content of your “.ssh” directory and add the relevant public keys to the “authorized_keys” file of the server.

$ ssh-copy-id <user>@<remote>

Push Changes to Git through SSH

Now that your keys are correctly configured for Git, you should be able to pull and push modifications to your Git repository.

Head over to the directory where your project files are stored.

$ cd /home/myproject

If you don’t have a Git repository, initialize one using the “git init” command.

$ git init

Initialized empty Git repository in /home/user/myproject/.git/

If there is already a “.git” file in your directory, it means that there is already a repository initialized.

Note: To get the content from your existing Git repository, use the “git clone” command.

Now that your Git repository is correctly configured, add the remote repository using the “git remote add” command.

$ git remote add origin git@<server_ip>:<path_to_git_repository>

On the server, if the “project.git” file (i.e the repository root) is located directly on the git user home directory, you would write

$ git remote add origin git@8.8.8.8:project.git

After adding your remote, make sure that your modifications are effective by running the “git remote -v” command.

$ git remote -v

origin   git@8.8.8.8:project.git (fetch)
origin   git@8.8.8.8:project.git (push)

Great!

Let’s now try to add some files in order to test if files can be pushed to your remote repository.

Create a README file using the “touch” command.

$ touch README

Add the files using the “git add” command and commit them using the “git commit” command.

$ git add .

$ git commit -m "This is the first commit of this repository"

Finally, push your modifications: the push operation should not require any password using the SSH method.

$ git push

Now, you have correctly configured SSH key-based authentication for your Git repository.

Conclusion

In this tutorial, you learned how you can generate SSH keys for Git easily using the ssh-keygen utility.

You learned that the same utility is used on Linux and on Windows. The directories used in order to store the keys are also the same.

How To Delete Local and Remote Tags on Git

How To Delete Local and Remote Tags on Git | Git Delete Tag for local & remote

Are you curious to learn how to delete local & remote tags on Git? Firstly, you should gain some knowledge about tags and git tags together with Git Commands. Generally, tags are utilized to tag particular commits that may be more significant than others. Also, you can use tags for bookmarking specific events like releases, bug fixes or simply to add an informative and descriptive note to a commit.

For instance, tags are often associated with genuine product releases on GitHub. But in some situations, you may require to delete git tags locally or remotely with ease. Now, it’s time to learn completely about the process of deleting Local and Remote Tags on Git. Use these available links and learn the concept that you are eagerly waiting for.

Describing Git Tags

Git tags support tagging particular points in the history of the repository and answer to them later. Once you create a tag, it won’t have a commit history. Actually, you can observe two types of tags supported by git. They are Annotated and Lightweight Tags. The major difference between them is the amount of metadata they store. One more difference is that annotated tags are public, and lightweight tags are private.

Now, you get some idea about git tags. So, take a look at the below explained delete local and remote tags in Git.

Delete a Local Git Tag

To delete a local Git tag, use the “git tag” command with the “-d” option.

$ git tag -d <tag_name>

For example, if you wanted to delete a local tag named “v1.0” on your commit list, you would run

$ git tag -d v1.0
Deleted tag 'v1.0' (was 808b598)

If you try to delete a Git tag that does not exist, you will simply be notified that the tag does not exist.

$ git tag -d v2.0
error: tag 'v2.0' not found.

If you want to make sure that tags were correctly deleted, simply list your existing tags using the tag command and the “-l” option.

$ git tag -l
<empty>

Delete a Remote Git Tag

To delete a remote Git tag, use the “git push” command with the “–delete” option and specify the tag name.

$ git push --delete origin tagname

Back to the previous example, if you want to delete the remote Git tag named “v1.0”, you would run

$ git push --delete origin v1.0

To https://github.com/SCHKN/repo.git
 - [deleted]         v1.0

To delete a remote Git tag, you can also use the “git push” command and specify the tag name using the ref’s syntax.

$ git push origin :refs/tags/<tag>

Back to the example, in order to delete a tag named “v1.0”, you would run

$ git push origin :refs/tags/v1.0

To https://github.com/SCHKN/repo.git
 - [deleted]         v1.0
Why should we specify the “refs/tags” instead of just specifying the tagname?

In some cases, your tag may have the same name as your branch.

If you tried to delete your Git tag without specifying the “refs/tags” you would get the following error

$ git push origin :v1.0

error: dst refspec v1.0 matches more than one.
error: failed to push some refs to '<repository>'

As a consequence, you need to specify that you are actually trying to delete a Git tag and not a Git repository.

Conclusion

In this tutorial, you have learned how you can easily delete a local and a remote Git tag. If you are interested to learn more about Git, check out our other tutorials on the subject such as:

How To Remove Files From Git Commit

How to Remove Files from Git Commit | Git Remove File from Commit Stage

In some working situations, developers add files or stages for commit on git repo. For better performance, you will need to remove files from Git commit to do more changes.

Git runs with three main spaces, they are the workspace (where you edit your files), the index (where you stage your files for commits), and the repository.

Do Check: GIT Commands

Let’s check this short & ultimate tutorial, to understand and learn how effectively & easily you can remove files from your Git commits, without losing your modifications.

Remove Files From Git Commit or Staging Area

In order to remove some files from a Git commit, use the “git reset” command with the “–soft” option and specify the commit before HEAD.

$ git reset --soft HEAD~1

When running this command, you will be presented with the files from the most recent commit (HEAD) and you will be able to commit them.

Now that your files are in the staging area, you can remove them (or unstage them) using the “git reset” command again.

$ git reset HEAD <file>

Note: This time, you are resetting from HEAD as you simply want to exclude files from your staging area

If you are simply not interested in this file anymore, you can use the “git rm” command in order to delete the file from the index (also called the staging area).

$ git rm --cached <file>

When you are done with the modifications, you can simply commit your changes again with the “–amend” option.

$ git commit --amend

To verify that the files were correctly removed from the repository, you can run the “git ls-files” command and check that the file does not appear in the file (if it was a new one of course)

$ git ls-files

<file1>
<file2>

Remove Single File from Committed Area

Removing file from the committed area needs 3 commands to be run, they are as follows-

git reset --soft HEAD^1

This command will undo the latest commit. Once you do git status, you will see files in the staging area. Now, we can easily remove it from the staging area, as mentioned in the previous point.

git rm --cached <file-name>

By performing the above command, the file will seem in the untracked file section. Now, we removed the single file, also you can commit back those remaining files by running the below command. So, let’s do it:

git commit -m "<your-message>"

Do Check: How To Delete File on Git

Remove File From Commit using Git Restore

Since Git 2.23, there is a new way to remove files from commit, but you will have to make sure that you are using a Git version greater or equal than 2.23.

$ git --version

git version 2.24.1

Note: Git 2.23 was released in August 2019 and you may not have this version already available on your computer. To install newer versions of Git, you can check this tutorial.

To remove files from commits, use the “git restore” command, specify the source using the “–source” option, and the file to be removed from the repository.

For example, in order to remove the file named “myfile” from the HEAD, you would write the following command

$ git restore --source=HEAD^ --staged  -- <file>

As an example, let’s pretend that you edited a file in your most recent commit on your “master” branch.

The file is correctly committed but you want to remove it from your Git repository.

To remove your file from the Git repository, you want first to restore it.

$ git restore --source=HEAD^ --staged  -- newfile

$ 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)
        modified:   newfile

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

As you can see, your file is back in the staging area.

From there, you have two choices, you can choose to edit your file in order to re-commit it again, or to simply delete it from your Git repository.

Remove File from Git Repository

In this section, we are going to describe the steps in order to remove the file from your Git repository.

First, you need to unstage your file as you won’t be able to remove it if it is staged.

To unstage a file, use the “git reset” command and specify the HEAD as the source.

$ git reset HEAD newfile

When your file is correctly unstaged, use the “git rm” command with the “–cached” option in order to remove this file from the Git index (this won’t delete the file on disk)

$ git rm --cached newfile

rm 'newfile'

Now if you check the repository status, you will be able to see that Git staged a deletion commit.

$ 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)
        deleted:    newfile

Now that your file is staged, simply use the “git commit” with the “–amend” option in order to amend the most recent commit from your repository.

$ git commit --amend

[master 90f8bb1] Commit from HEAD
 Date: Fri Dec 20 03:29:50 2019 -0500
 1 file changed, 2 deletions(-)
 delete mode 100644 newfile

As you can see, this won’t create a new commit but it will essentially modify the most recent commit in order to include your changes.

Remove Specific File from Git Commit

In some cases, you don’t want all the files to be staged again: you only one to modify one very specific file of your repository.

In order to remove a specific file from a Git commit, use the “git reset” command with the “–soft” option, specify the commit before HEAD and the file that you want to remove.

$ git reset HEAD^ -- <file>

When you are done with the modifications, your file will be back in the staging area.

First, you can choose to remove the file from the staging area by using the “git reset” command and specify that you want to reset from the HEAD.

$ git reset HEAD <file>

Note: It does not mean that you will lose the changes on this file, just that the file will be removed from the staging area.

If you want to completely remove the file from the index, you will have to use the “git rm” command with the “–cached” option.

$ git rm --cached <file>

In order to make sure that your file was correctly removed from the staging area, use the “git ls-files” command to list files that belong to the index.

$ git ls-files

When you are completely done with your modifications, you can amend the commit you removed the files from by using the “git commit” command with the “–amend” option.

$ git commit --amend

Conclusion

In this tutorial, you learned how you can easily remove files from commit using the “git reset” command. You also learned to remove files on newer versions of Git using the “git restore” command but you will have to make sure that you have the most recent Git version (>= 2.23).