Since graduating from my coding bootcamp, I've worked on multiple solo projects and collaborated on many more. And no matter what language I was using – whether it was TypeScript or Python – one thing remained the same: Git.
Git is essential to my workflow, helping me organize projects and collaborate efficiently.
In this tutorial, I will walk you through 21 essential Git commands that'll instantly boost your productivity and streamline your development workflow.
Before we start, a few things you should know:
Git is not GitHub. Git is a version control system, while GitHub is a platform that hosts Git repositories. They work together, but are distinct tools.
What is a version control system? It is a tool that records every change made to a set of files (like your code), allowing you to revert to earlier versions, compare changes, and collaborate more effectively.
In this tutorial, you will find 21 commands that will provide a good starting point for learning Git, but Git is more complex than that. In the Resources section, you will find excellent further reading—the same resources I used when I was first learning Git.
In Git, files go through three main stages:
Unstaged (Modified): This is when you've made changes to a file in your working directory, but Git isn't tracking those specific changes yet.
Staged: You've used the git add
command to tell Git that you want to include these changes in the next commit. Think of it as preparing your changes to be saved.
Committed: You've used the git commit
command to save the changes in the staging area to your Git repository. This creates a permanent record of those changes.
Table of Contents
- Initializing and Cloning
- Staging and Committing Changes
- Working with Remote Repositories and Merging
- Branching
- Inspecting and Comparing
- Undoing Changes
- Other Commands
- Resources
Initializing and Cloning
Initializing a new repository or cloning an existing one are likely the very first things you'll do with Git. These commands let you start a new version-controlled project or join an existing one by getting a local copy.
1. git init
Purpose: Initializes a new Git repository.
Use Case: You are starting a new project and want to use Git for version control. This command creates the necessary Git infrastructure in your project directory.
Command:
git init
Often used with:
git add . # Adds all files in the directory to the staging area.
git commit -m "Initial commit" # Creates the first commit.
2. git clone
Purpose: Clones an existing repository into a new directory.
Use Case: You want to work on a project that's already hosted on a remote repository like GitHub. This command copies the entire repository to your local machine.
Command:
git clone https://github.com/user/repo.git
Often used with:
cd <repository-name> # Changes the directory to the cloned repository.
git remote -v # Verifies the remote repository URL.
Staging and Committing Changes
Staging and committing in Git records your changes. Staging prepares a snapshot, and committing saves it. These commands are crucial for saving your work, creating project history, and reverting to previous states.
3. git add
Purpose: Adds changes in the working directory to the staging area, preparing them for the next commit.
Use Case: You've made changes to some files and are ready to save them. You use git add
to select which of those changes you want to include in the next commit.
You can add all changes by using a single dot (.), or you can add specific file or files. See example:
Command:
git add . # Adds all changes in the current directory and its subdirectories
git add *.txt # Adds all files ending in .txt
git add file1.txt file2.txt # Adds specific files
Often used with:
git status # Common to use before `git add` to see what files have changed and which ones are untracked.
git commit -m "Commit message" # Commits the staged changes.
4. git commit
Purpose: Records the changes currently in the staging area to the repository. This creates a permanent record of your work.
Use Case: You've staged the changes you want to save, and now you're ready to create a snapshot of your project at this point in time.
Command:
git commit -m "Descriptive commit message"
git commit -a -m "Commit message" # Stages all changes and commits in one command (use with caution)
Best practice: Always write clear, descriptive commit messages. This significantly improves collaboration and makes it easier to understand the history of your project. Although the -a option can be used as a shortcut, explicitly staging changes with git add
provides more control and is generally preferred.
Often used with:
git log # View the project's commit history. Often used to review your commits.
git push # Upload your local commits to a remote repository (e.g., GitHub, GitLab). Typically used after committing.
5. git push
Purpose: Updates the remote repository with local commits.
Use Case: You want to upload local changes to a remote repository like GitHub.
git push origin main # Push local commits to main branch
Often used with:
git remote add origin <remote_url> # Adds the remote repository.
git pull origin main # Ensures you have the latest changes before pushing.
Working with Remote Repositories and Merging
Collaboration is key in software development. To work with others and keep your codebase up-to-date, you need to interact with remote repositories. Fetching changes, merging updates, and managing remote connections are essential to teamwork, allowing you to share your work, integrate contributions from others, and maintain a synchronized project. Here are some important commands you should know:
6. git fetch
Purpose: Downloads changes from a remote repository to your local repository.
Think of it as getting the latest information from the remote, but not yet applying it.
Use Case: You want to see what changes have been made on the remote before deciding whether or not to incorporate them into your work. This is a good way to review changes before merging.
Command:
git fetch origin # Get changes from the 'origin' remote, but doesn't merge them.
Often used with:
git merge origin/<branch_name> # Merges the fetched changes.
git remote -v # Verifies the remote repository.
7. git merge
Purpose: Takes the changes from the specified branch and applies them to your current branch.
If there are conflicts (e.g., the same lines of code were modified in both branches), you'll need to resolve them manually.
Use Case: You want to incorporate the latest changes from the remote into your working branch. Or, you've finished working on a feature branch and want to merge it back into the main branch.
Command:
git merge new-feature # Merge the 'new-feature' branch into the current branch.
Often used with:
git checkout <branch_name> # Switches to the target branch.
git branch -d <branch_name> # Deletes a merged branch.
8. git pull
Purpose: Downloads changes from the remote and immediately integrates them into your current branch.
git pull
is essentially a shortcut for git fetch
followed by git merge
. When you run git pull origin main
(for example), Git does the following behind the scenes:
git fetch origin:
Fetches the latest changes from the main branch on the origin remote and updates your local origin/main branch.
git merge origin/main
: Merges the changes from your local origin/main branch into your currently active branch (e.g., your local main branch).
Use Case: You want to quickly update your current branch with the latest changes from the remote. This is commonly used when you're working on a shared branch and want to keep your local copy synchronized.
Command:
git pull origin main # Pulls changes from the 'main' branch of the 'origin' remote.
Often used with:
git log origin/main # View the commit history of the remote 'main' branch to see what changes have been made.
git diff origin/main # See the specific differences between your local 'main' branch and the remote 'main' branch before pulling. This helps you understand exactly what will change.
9. git rebase
Purpose: Integrates changes from one branch into another by rewriting the commit history to create a linear sequence of commits.
git rebase
is an alternative command to git merge.
The major difference between the two is that git merge
applies the fetched changes on top of your current branch, creating an additional merge commit.
Rebase, on the other hand, applies the fetched changes as a new base for your branch and then replays your changes on top of that new base.
Afterward, it rewrites the history, incorporating any merge changes into your latest commit. This allows you to avoid unnecessary merge commits and is therefore often preferred for maintaining a clean and less verbose history.
Rebase is frequently used as the default strategy for git pull
by setting git config --global pull.rebase true
.
Use Case: You want to integrate changes from one branch into another by rewriting history.
Command:
git checkout feature-branch # Switch to the feature branch that you want to rebase.
git rebase main # Rebase the 'feature-branch' onto 'main'. This replays the commits from 'feature-branch' on top of 'main'.
Often used with:
git log # Checks the commit history after rebasing.
10. git remote
Purpose: Manages set of tracked repositories.
Use Case: You want to add, remove, and list remote repositories.
Command:
git remote add origin https://github.com/user/repo.git
Often used with:
git remote -v # Lists remote repositories and their URLs.
git fetch <remote_name> # Fetches changes from a remote repository.
Branching
Branching is a powerful Git tool that lets you create parallel lines of development. It allows you to isolate changes, experiment safely, and manage different versions of your project effectively, before merging those changes.
11. git branch
Purpose: Manages branches.
Usage: Use git branch
to create, list, switch between, delete, and rename branches. This is crucial for managing concurrent development, isolating features, and keeping the main branch stable.
Command:
git branch
# Lists all branches
git branch new-feature
# Creates a new branch named "new-feature"
git checkout -b <branch_name>
# Creates a new branch and switches to it.
Often used with:
git checkout <branch_name> # Switches to a branch.
git merge <branch_name> # Merges a branch.
12. git checkout
Purpose: Switches branches or restores working tree files.
Use Case: You want to navigate between different branches.
Command:
git checkout new-feature # Switches the current branch to 'new-feature'.
#Any changes made after this point will be committed to the 'new-feature' branch.
Often used with:
git branch <branch_name> # Creates a new branch.
Inspecting and Comparing
Git provides powerful tools for inspecting and comparing your repository. Understanding commit logs, differences between versions, and details of specific changes is key to navigating your project's history, debugging issues, and understanding the evolution of your codebase.
13. git log
Purpose: Shows the commit logs.
Use Case: At its most basic, git log lets you see the order in which changes were made to the project. This is crucial for understanding how the project has evolved over time, which features were added when, and what bug fixes were implemented.
Note: When the output of git log
is too long, Git uses a pager (often less or sometimes vim) to display it.
If less is used, press q to exit.
If vim is used, press Esc, then type :q and press Enter to exit.
Command:
git log
Often used with:
git show <commit_hash> # Shows details of a specific commit.
git diff <commit_hash1> <commit_hash2> # Shows differences between two commits.
14. git diff
Purpose: Displays changes between commits/working tree.
Use Case: You want to compare changes in the repository.
Command:
git diff # Shows changes between the working directory and the staging area.
Often used with:
git add . # Stages all changes in the current directory, preparing them for a commit.
git commit -m "Commit message" # Commits the changes.
15. git show
Purpose: Shows various types of objects.
Use Case: You want to display information about a specific commit, tag, or file.
Command:
git show <commit-id> # Displays information about the specified commit.
Often used with:
git log # Finds the commit ID.
git diff <commit-id1> <commit-id2> # Compares changes between commits.
Undoing Changes
Git is designed to let you undo changes effectively. Knowing how to reset commits, unstage files, or stash changes is crucial for recovering from errors, cleaning up your working directory, and confidently experimenting without fear of permanently breaking things.
16. git reset
Purpose: Resets the current HEAD to the specified state.
This command is powerful and has different effects depending on the options used, particularly on the staging area and working directory. It's crucial to understand these differences to avoid accidental data loss.
Use Case: You want to undo changes, but how you undo them is determined by the specific reset type.
Key Differences and Potential Data Loss:
Option | HEAD Pointer | Staging Area | Working Directory | Data Loss Potential |
---|---|---|---|---|
--soft |
Moves | Unchanged | Unchanged | No |
--mixed |
Moves | Resets to match the new HEAD | Modified: unstaged changes from the old HEAD | Low |
--hard |
Moves | Resets to match the new HEAD | Resets to match the new HEAD (loses unstaged changes) | High |
Command:
git reset HEAD file-name # Unstages a specific file
git reset --hard HEAD # Discards all changes in the working directory and staging area
Often used with:
git status # Checks the status after resetting.
git checkout . # Discards changes in the working directory.
17. git stash
Purpose: Temporarily saves uncommitted changes.
Use Case: When you want to switch branches but don't want to commit changes yet and don't want to lose them, git stash
will help.
Command:
git stash
# Saves changes
git stash pop
# Restores saved changes
Often used with:
git checkout <branch_name> # Switches to another branch.
git stash list # Lists all stashed changes.
Other Commands
18. git tag
Purpose: Creates, lists, deletes or verifies a tag object signed with GPG.
Use Case: You want to mark specific points in history as important (e.g., releases).
Command:
git tag -a v1.0 -m "Version 1.0 release"
Often used with:
git tag # Lists all tags.
git show v1.0 # Shows details of the v1.0 tag.
git push origin --tags # Pushes tags to the remote repository.
19. git rm
Purpose: Removes files from the working tree and from the index (staging area).
Use Case: You want to delete files from the repository.
Command:
git rm file-name # Removes the file from the working directory and stages the deletion for the next commit.
Often used with:
git commit -m "Removed file-name" # Commits the removal.
git status # Checks the status after removing the file.
git add . # Stages the removal.
20. git status
Purpose: Displays the state of the working directory and staging area.
Use Case: The git status
command is essential for understanding the current state of your Git repository. It provides a summary of changes you've made to your project files, distinguishing between those that are tracked by Git, those that are staged for commit, and those that are untracked.
Command:
git status # Shows the current status of the working directory and staging area
Often used with:
git add . # Stages changes.
git commit -m "Commit message" # Commits changes.
21. git reflog
Purpose: Records updates to the tip of branches and other symbolic refs.
It's a history of where your HEAD and branch pointers have been, allowing you to recover from accidental changes or understand your past actions. Think of it as a local history of your Git actions that is not shared with others when pushing to a remote repository.
Use Case:
- Recovering lost commits: If you accidentally delete a branch or overwrite changes, reflog can help you find the commit hash before the mistake.
- Understanding your steps: Reflog shows you the sequence of commands you've executed, which can be useful for debugging or retracing your steps.
- Identifying the source of a change: If you see unexpected changes, reflog can help you pinpoint when and how they were introduced.
Command:
git reflog show [ref] # Shows reflog for [ref] (default: current branch)
git reflog show --all # Shows reflog for all refs.
Often used with:
git checkout <commit-hash> # Go to a reflog commit.
Resources
-
git help
: The fastest way to get help with a specific Git command. Just typegit help <command>
in your terminal. - Official Git Documentation: https://git-scm.com/ - For in-depth information and advanced topics.
- Pro Git Book: https://git-scm.com/book/en/v2 - A great resource for learning Git from scratch or deepening your understanding.
Tip: Start with the Pro Git book if you're new to Git.
Final Thoughts
Learning Git was a game-changer for me. These are the commands I use most often, and they've significantly improved my productivity. I hope they improve yours too.
Top comments (0)