Mastering Git Commands: Essential Tips and Tricks

Akhil Regonda
9 min readApr 16, 2024

--

Introduction:

Ah, Git, the love/hate relationship that affects every developer. ;) It’s that magical tool that seems to make version control effortless but frequently leaves us scratching our heads in frustration. Fear not, brave programmer! This article will take you on a journey to learn the fundamental Git commands. A thrilling journey through the world of commits, merges, and pushes. Shall we get started?

Section 1: Understanding Git Basics

1.1. What is Git?

Git is a distributed version control system that tracks file changes and manages teamwork. It allows developers to work on projects simultaneously without overwriting each other’s changes. Unlike centralized version control systems, Git stores a complete copy of the project’s history on every developer’s computer (local repo), enabling offline work and collaboration.

1.2. Basic Concepts

  • Repositories: A repository, also known as a repo, is a folder that contains your project's files, along with the record of each version of those files. Typically, every developer has a copy of the repository on their computer, and there can also be a central repository hosted on a remote server (such as GitHub or GitLab) for collaboration purposes.
  • Commits: A commit is a record of your project at a particular moment in time. Each commit captures the changes made to the files since the last commit and a commit message that describes these changes. Commits help you track the history of your project and enable you to go back to previous states if required.
  • Branches: "Branches" refer to parallel lines of development that diverge from the main line of development, usually referred to as the "master" or "main" branch. Developers can create branches to work on new features or fixes without affecting the main codebase, which allows them to experiment freely and work on their own code without disrupting the main project. Once the changes are complete, they can be merged back into the main branch, incorporating the new features or fixes into the overall project.
  • Remotes: When using Git, remotes refer to repositories that are hosted on remote servers. Whenever you clone a repository, Git will automatically create an "origin" remote that points to the original repository. To collaborate with other teams or developers, you can add additional remotes.

Having a solid grasp of repositories, commits, branches, and remotes is essential for the effective use of Git. With these concepts, you'll be well-equipped to manage projects and collaborate using Git.

Section 2: Essential Git Commands

2.1. git init

The git init command initializes a new Git repository in the current directory, creating a hidden subdirectory called ".git" that stores all the metadata and configuration for the repository.

Usage:
To initialize a new Git repository, navigate to the root directory of your project in the terminal and run git init.

cd /path/to/your/project
git init

2.2. git clone

The git clone command creates a copy of an existing Git repository from a remote URL and sends it to your local machine.

Usage:
To clone a repository, use the git clone command followed by the URL of the repository you want to clone.

git clone https://github.com/user/repository.git

2.3. git add

The git add command adds changes from the working directory to the staging area, preparing them to be committed to the repository.

Usage:
To add changes, specify the files or directories you want to stage, either by their names or using wildcards.

git add file1.txt
git add .

2.4. git commit

The git commit command saves the changes staged in the staging area to the repository, creating a new commit with a commit message.

Usage:
After adding changes with git add, run git commit followed by the -m flag and a descriptive commit message enclosed in quotes.

git commit -m "Add new feature"

2.5. git status

The git status command displays the current state of the repository, showing which files have been modified, staged, or untracked.

Usage:
Run git status in the terminal to see the current status of your repository.

git status

2.6. git log

The git log command displays a list of commits in reverse chronological order, showing the commit hash, author, date, and commit message.

Usage:
Run git log in the terminal, see the repository's commit history.

git log

2.7. git branch

The git branch command lists creates, or deletes branches in the repository.

Usage:
To list existing branches, run git branch. To create a new branch, use git branch <branch-name>. To delete a branch, use git branch -d <branch-name>.

git branch
git branch new-feature
git branch -d old-feature

2.8. git checkout

The git checkout command switches between branches or restores files to a previous state.

Usage:
To switch branches, run git checkout <branch-name>. To restore files to a previous commit, use git checkout <commit-hash> -- <file>.

git checkout main
git checkout HEAD~1 -- file.txt

2.9. git merge

The git merge command combines changes from one branch into another, integrating new features or fixes.

Usage:
First, switch to the branch you want to merge changes into. Then, run git merge <branch-name> to merge changes from the specified branch.

git checkout main
git merge new-feature

2.10. git pull

The git pull command fetches changes from a remote repository and merges them into the current branch on your local machine.

Usage:
Run git pull in the terminal to fetch and merge changes from the default remote repository (usually called "origin").

git pull

2.11. git push

The git push the command sends your local commits to a remote repository, making your changes available to others.

Usage:
After committing changes locally, run git push followed by the name of the remote repository and the branch you want to push.

git push origin main

2.12. git stash

The git stash command temporarily shelves changes in your working directory, allowing you to switch to a different branch or address an urgent task without committing incomplete changes.

Usage:
To stash changes, run git stash. You can later apply these changes to your working directory with git stash apply or git stash pop.

git stash

git stash apply
The git stash apply the command applies the most recent stash to your working directory, reapplying the stashed changes.

Usage:
After running git stash apply, the stash is still kept in the stash list, allowing you to apply it again if needed.

git stash apply

git stash pop
The git stash pop the command also applies the most recent stash to your working directory, removing that stash from the stash list.

Usage:
After running git stash popThe stash that was popped has been removed from the stash list, so you won't be able to apply it again unless you create a new stash with additional changes.

git stash pop

git stash apply reapplies the most recent stash without removing it from the stash list while git stash pop applying the most recent stash and removing it from the stash list in one step.

Git commands for raising a pull request (PR)

# 1. Clone the repository to your local machine
git clone https://github.com/user/repository.git

# 2. Navigate into the repository directory
cd repository

# 3. Create a new branch for your feature or bug fix
git checkout -b feature-branch

# 4. Make changes to the codebase in your feature branch
# - Modify existing files
# - Add new files
# - Implement your feature or fix bugs

# 5. Add and commit your changes to the feature branch
git add .
git commit -m "Implemented feature A"

# 6. Push your feature branch to the remote repository
git push origin feature-branch

# 7. Visit the repository on GitHub in your web browser
# - Navigate to the "Pull Requests" tab
# - Click on the "New pull request" button

# 8. Select the base and compare branches for the pull request
# - Choose the base branch (usually "main" or "master")
# - Choose the compare branch (your feature branch)

# 9. Review your changes in the pull request
# - Verify that the changes are correct and complete
# - Add a title and description to the pull request to explain the changes

# 10. Submit the pull request
# - Click on the "Create pull request" button

# 11. Communicate and collaborate on the pull request
# - Discuss any feedback or changes requested by reviewers
# - Make additional commits and push changes to the feature branch as needed

# 12. Once approved, merge the pull request
# - Click on the "Merge pull request" button
# - Choose an appropriate merge strategy (e.g., merge commit or squash and merge)

# 13. Delete the feature branch (optional)
# - After the pull request is merged, you can delete the feature branch locally and remotely
git checkout main
git pull origin main
git branch -d feature-branch
git push origin --delete feature-branch

Section 3: Advanced Git Techniques

3.1. git rebase

The git rebase command allows you to reapply commits from one branch onto another branch. It's often used to maintain a clean and linear history by incorporating changes from one branch into another in a more organized manner than traditional merging.

Usage:
To rebase your current branch onto another branch, use git rebase <base-branch>. You can also use interactive rebase git rebase -i <base-branch> to modify, reorder, or squash commits during the rebase process.

git checkout feature-branch
git rebase main

3.2. git reset

The git reset command allows you to reset the current branch to a specific commit by discarding changes or moving the branch pointer to a previous state. It's often used to undo commits or unstaged changes.

Usage:
To reset the current branch to a specific commit, use git reset <commit> with one of the following options:

  • --soft: Keep changes in the working directory.
  • --mixed: Reset the staging area but keep changes in the working directory (default).
  • --hard: Discard changes in the staging area and working directory.
git reset --soft HEAD~1

3.3. git cherry-pick

The git cherry-pick command allows you to apply specific commits from one branch onto another branch. It's useful for selectively incorporating changes from one branch into another without merging the entire branch.

Usage:
To cherry-pick a commit onto the current branch, use git cherry-pick <commit> with the commit hash of the desired commit.

git cherry-pick abc123

Understanding these advanced Git techniques will empower you to perform more sophisticated version control operations, such as managing branches, manipulating commit history, and debugging issues in your codebase.

Section 4: Tips and Tricks for Efficiency

4.1. Committing Frequently

Making small, frequent commits helps keep your commit history organized and makes it easier to track progress and revert changes if needed.

Tips:

  • Commit related changes together to create meaningful commits.
  • Use descriptive commit messages that explain the purpose of each change.
git add .
git commit -m "Add feature A"
git add .
git commit -m "Fix issue B"

4.2. Writing Descriptive Commit Messages

Writing clear and descriptive commit messages is crucial for effective collaboration and code maintenance. A well-crafted commit message provides context and helps others understand the purpose of the changes.

Tips:

  • Start the commit message with a short, imperative sentence (e.g., “Added”, “Fixed”, “Update”).
  • Provide additional details in the body of the message, if necessary.
git commit -m "Added new feature X"

4.3. Using Aliases

Git aliases can save time by creating shortcuts for commonly used commands, including complex or frequent ones.

Tips:

  • Use meaningful aliases that are easy to remember.
  • Avoid overriding existing Git commands or aliases.
git config --global alias.co checkout
git config --global alias.ci commit

4.4. Utilizing Git GUIs and Tools

Graphical User Interfaces (GUIs) and third-party tools provide alternative interfaces for interacting with Git repositories. They offer visualizations, workflows, and additional features to improve your Git experience.

Tips:

  • Explore different Git GUIs and tools to find one that suits your preferences and workflow.
  • Familiarize yourself with the features offered by the tool to leverage its full potential.
Sourcetree
GitKraken
GitHub Desktop

4.5. Exploring Git Documentation

Git documentation serves as a comprehensive guide to mastering Git commands, concepts, and best practices. It includes detailed explanations, usage examples, and references to help you navigate the complexities of version control.

Tips:

  • Refer to the official Git documentation (https://git-scm.com/docs) for comprehensive information on Git commands and concepts.
  • Explore community resources, tutorials, and forums for additional insights and tips.
git help <command>

Incorporating these tips and tricks into your Git workflow will help boost productivity, manage projects more effectively, and collaborate better with others.

Conclusion:

Great job on finishing this extensive guide that aims to help you master Git commands and techniques! We've covered everything from the basics of version control using Git to advanced tips and tricks to improve your efficiency. At this point, you should have a firm grasp of Git's functionality and how to use its features to manage your projects effectively.

Git is a powerful tool that enables developers to collaborate, track changes, and maintain version history with ease. Whether you are working on a project alone or with a team, Git offers the flexibility and control you need to manage your codebase efficiently.

By following the techniques and best practices outlined in this article, you will be well-equipped to handle version control challenges, streamline your workflow, and collaborate seamlessly with others. Keep learning, keep practicing.

Thank you! Happy coding!

--

--

Akhil Regonda

Frontend & Full stack developer with a passion for creating engaging user experiences.