DEV Community

Cover image for 10 Must-Know Git Commands for Every Developer
Mukesh Kuiry
Mukesh Kuiry

Posted on

10 Must-Know Git Commands for Every Developer

Understanding Git and GitHub is crucial for any developer, providing effective version control and code management. Proficiency in these tools sets you apart and enhances your productivity. In this blog post, we will explore a set of Git commands to kickstart your journey into software development.

Git Vocabulary

Before delving into the commands, let's acquaint ourselves with some Git terminologies. This understanding will not only help you grasp Git better but also provide a foundation for your overall comprehension.

Repository

A repository, or repo, serves as a storage space where your project's source code and its version history are stored.

Working Directory

The working directory is where you currently make changes to your project, housing the files you are actively working on.

Staging

Staging acts as an intermediate area between the repository and your working directory. It's where you add changes before committing them to the main repository.

Commit

A commit is a snapshot of proposed changes to the stage, identified by a unique identifier (SHA-1 hash) and accompanied by a commit message.

Branch

A branch represents a parallel version of your repository, facilitating work on different features or bug fixes independently.

Merge

Merging involves combining proposed changes into the main repository, often utilized to integrate new features into the main project.

Pull

Pulling refers to fetching code from any remote repository and merging it into your local repository, i.e., working directory.

Push

Pushing involves sending your local changes to any remote branch of any repository.

Clone

Cloning is the process of creating a local copy of the main repository, establishing a connection for efficient pull and push.

Fetch

Fetching downloads changes from any remote repository to the local repository, without directly merging them into your local repository. It is useful for reviewing changes before merging.

Fork

Forking creates a personal copy of someone else's repository on your GitHub account, enabling changes without affecting the original repository.

Conflict

A conflict arises when two or more branches have changes in the same part of the code, and Git cannot directly merge them.

Head

In Git, HEAD is a pointer/reference always pointing to your latest commit in the current branch. When you make a new commit, HEAD moves to the top of your commit.
 

Now, let's explore the 10 Git commands one by one.

begin meme

1 - Adding and Committing Files Together

Traditionally, in Git, we use the git add * command to stage all modified files for a subsequent commit. Subsequently, we use the git commit -m "commitMessage" command to commit these changes. However, a more streamlined command exists, achieving both tasks in a single step:



git commit -am "commitMessage"


Enter fullscreen mode Exit fullscreen mode

The -am flag allows us to stage these changes and commit them in one efficient operation.

2 - Creating and Switching to a Git Branch

Similar to the previous scenario, another command combines the functionality of two commands. Instead of using separate commands, use git branch branchName to create a branch and git checkout branchName to switch to it. Achieve both tasks in a single step with the following command:



git checkout -b branchName


Enter fullscreen mode Exit fullscreen mode

The -b flag with the git checkout command allows us to create a new branch and immediately switch to it.

3 - Delete a Git Branch

To delete a branch in Git, use the git branch -d or git branch -D command. The -d option is for a safe deletion, only deleting the branch if fully merged into the current branch. The -D option is for forceful deletion, regardless of whether it's fully merged. Here are the commands:

Safe deletion (checks for merge):



git branch -d branchName


Enter fullscreen mode Exit fullscreen mode

Forceful deletion (doesn’t check for merge):



git branch -D branchName


Enter fullscreen mode Exit fullscreen mode

4 - Renaming a Git Branch

To rename a branch, use the git branch -m command followed by the current branch name and the new desired branch name. For example, to rename a branch called oldBranch to newBranch, run:



git branch -m oldBranch newBranch


Enter fullscreen mode Exit fullscreen mode

If you want to rename the current branch where you are working, without specifying the old name, use the following command:



git branch -m newBranchName


Enter fullscreen mode Exit fullscreen mode

Here, you don’t need to specify the old branch name because Git will assume you want to rename the current branch to the new name.

5 - Unstaging a Specific File

Occasionally, you may want to remove a particular file from the staging area, allowing additional modifications before committing. Use:



git reset filename


Enter fullscreen mode Exit fullscreen mode

This will un-stage that file while keeping your changes intact.

6 - Discarding Changes to a Specific File

To completely discard changes made to a specific file and revert it to its last committed state, use:



git checkout -- filename


Enter fullscreen mode Exit fullscreen mode

This command ensures the file returns to its previous state, undoing recent modifications. It’s a helpful way to start fresh on a particular file without affecting the rest of your changes.

7 - Updating Your Last Git Commit

Imagine you’ve just made a commit in your Git repository, but then you realize that you forgot to include a change in that commit, or perhaps you want to fix the commit message itself. You don’t want to create a whole new commit for this small change. Instead, you want to add it to the previous commit. This is where you can use the command:



git commit --amend -m 'message'


Enter fullscreen mode Exit fullscreen mode

This command modifies the most recent commit you made, combining any staged changes with your new comment to create an updated commit.

A thing to remember is that if you have already pushed the commit to a remote repository, you will need to force push the changes using git push --force to update the remote branch. A standard git push operation appends a new commit to your remote repository rather than modifying the last commit.

8 - Stashing Changes

Imagine you’re working on two different branches, A and B. While making changes in branch A, your team asks you to fix a bug in branch B. When you attempt to switch to branch B using git checkout B, Git prevents it, displaying an error:

Unable to change branch

We can commit our changes as suggested by the error message. But committing is

more like a fixed point in time, not an ongoing work in progress. This is where we can apply the error message’s second suggestion and use the stash feature. Use this command for stashing your changes:



git stash


Enter fullscreen mode Exit fullscreen mode

git stash temporarily saves changes that you're not ready to commit, allowing you to switch branches or work on other tasks without committing incomplete work.

To reapply stashed changes in your branch, use git stash apply or git stash pop. Both commands restore the latest stashed changes. Stash applying simply restores the changes, while popping restores the changes and removes them from the stash. You can read more about stashing over here.

9 - Reverting Git Commits

Imagine you’re working on a Git project, and you discover that a particular commit introduced some undesirable changes. You need to reverse those changes without erasing the commit from history. Use the following command to undo that particular commit:



git revert commitHash


Enter fullscreen mode Exit fullscreen mode

It’s a safe and non-destructive way to correct errors or unwanted alterations in your project.

For instance, let’s say you have a series of commits:

  • Commit A
  • Commit B (undesirable changes introduced here)
  • Commit C
  • Commit D

To reverse the effects of Commit B, run:



git revert commitHashOfB


Enter fullscreen mode Exit fullscreen mode

Git will create a new commit, let’s call it Commit E, which negates the changes introduced by Commit B. Commit E becomes the latest commit in your branch, and the project now reflects the state it would have been in if Commit B had never happened.

If you’re wondering how to retrieve a commit hash, it’s straightforward using git reflog. In the screenshot below, the highlighted portions represent the commit hashes that you can easily copy:

Commit Hashes

10 - Resetting Git Commits

Let’s assume you’ve made a commit to your project. However, upon inspection, you realize that you need to adjust or completely undo your last commit. For such a scenario, Git provides these powerful commands:

Soft reset



git reset --soft HEAD^


Enter fullscreen mode Exit fullscreen mode

When you use git reset --soft HEAD^, you are performing a soft reset. This command allows you to backtrack on your last commit while preserving all your changes in the staging area. In simple words, you can easily uncommit while retaining your code changes, using this command. It is handy when you need to revise the last commit, perhaps to add more changes before committing again.

Mixed reset



git reset --mixed HEAD^


Enter fullscreen mode Exit fullscreen mode

This is the default behavior when you use git reset HEAD^ without specifying --soft or --hard. It un-commits the last commit and removes its changes from the staging area. However, it keeps these changes in your working directory. It is helpful when you want to un-commit the last commit and make changes from scratch while keeping the changes in your working directory before re-committing.

Hard reset



git reset --hard HEAD^


Enter fullscreen mode Exit fullscreen mode

Now, let’s talk about git reset --hard HEAD^. It completely erases the last commit along with all the associated changes from your Git history. When you use --hard flag, there's no going back. So use this with extreme caution when you want to discard the last commit and all its changes permanently.

Thank you for reading. I hope this post is helpful, and you learned some new commands. If you have any further questions, don’t hesitate to reach out. Feel free to share any Git commands you tend to use in your daily routine and find super handy. :)

Connect with me
LinkedIn
X (formerly Twitter)

Top comments (21)

Collapse
 
random_ti profile image
Random

Awesome Guide on Github Commands 🔥

Thanks for sharing this💖

Collapse
 
mukeshkuiry profile image
Mukesh Kuiry

Thanks for appreciation! ❤️

Collapse
 
issa1960 profile image
ISSA NDAGI UMARU

Wow interesting 👍🏾

Collapse
 
soansuiyan profile image
SoanSuiyan

prueba

Collapse
 
tijuana22 profile image
Tijuana Hunt

Thanks for sharing!

Collapse
 
omi profile image
Omi

that was great, but im stil confused on git resest part
could u just had added some visualize or example would be better

Collapse
 
mukeshkuiry profile image
Mukesh Kuiry

For example, your company wants to ship their product every Saturday night, but you, as a developer, mistakenly committed the changes before Saturday to the main

In that case, you need to remove the changes from the main branch. Removing the changes one by one may be complex. In that case, you just need to run the git reset command to remove the last commit.

Hope that makes sense.

Collapse
 
dev_saheb profile image
NayemulSCode

really good article 👌

Collapse
 
vepifanio profile image
Victor Epifânio

Awesome content!
Thanks for sharing! 💖

Collapse
 
drgrey profile image
Dr-Grey

Would probably be a good idea to include a script that'd run on demand or per schedule that does pull for number of branches specified .

Collapse
 
mukeshkuiry profile image
Mukesh Kuiry

Yeah, that's a good idea, but it may not be efficient for the project, which took a long time to build. As it may be more prone to errors, like conflicts.

Collapse
 
sripartha99 profile image
Parthasarathy

Thank you for sharing such powerful git commands... Very useful 😀👍🏻

Collapse
 
dipayansukul profile image
Dipayan Sukul

Good content for those who are starting up.

Collapse
 
mukeshkuiry profile image
Mukesh Kuiry

Yeah, thanks 🙏

Some comments have been hidden by the post's author - find out more