Git is a powerful tool, but many developers only scratch the surface of what it can do. In this post, I’ll share 10 lesser-known Git tricks that will boost your productivity and make you look like a Git wizard.
1. Undo Your Last Commit (Without Losing Changes)
There are times when you accidentally commit too soon, maybe before adding an important file or making a final review. Instead of worrying or starting over, you can easily undo the last commit while keeping your changes intact.
To do this, use the following command:
git reset --soft HEAD~1
This moves your last commit back to the staging area, keeping your changes intact.
What This Does:
-
git reset
moves the commit pointer back to the previous commit. -
--soft
ensures that all your changes remain staged, so you don’t lose any progress. -
HEAD~1
refers to the last commit, meaning it will undo only the most recent one.
When to Use It:
- You committed too early and need to add more changes.
- You forgot to include a file in the commit.
- You want to modify the commit message before pushing.
After running this command, your changes will still be in the staging area. You can now:
✅ Add more files using git add .
✅ Modify your commit message using git commit -m "New message"
2. Quickly Switch to the Previous Branch
Tired of typing long branch names when switching back and forth between two branches? There's a simple shortcut that lets you instantly jump to the last branch you were on without manually typing its name.
You can simply use:
git checkout -
This switches you back to the last branch you were on.
What This Does:
- The
-
flag tells Git to switch to the previous branch, no matter what its name is. - This is especially useful when frequently switching between two branches while coding or reviewing changes.
3. Stash Only Certain Files
Sometimes, you don’t want to stash all your changes—just a specific file or two. Instead of stashing everything and losing track of your work, you can stash only the files you need while leaving the rest untouched.
To do this, use:
git stash push -m "Stashing only index.js" index.js
This stashes only index.js
, leaving other changes untouched.
What This Does:
-
git stash push
creates a new stash entry. -
-m "message"
adds a description to help you identify the stash later. -
-- index.js
specifies that onlyindex.js
should be stashed.
How to Apply the Stashed File Back:
Later, when you’re ready to bring back index.js
, use:
git stash pop
or if you have multiple stashes, check the list first:
git stash list
Then, apply a specific stash using:
git stash apply stash@{n}
(Replace n
with the correct stash index.)
4. See Who Modified a Specific Line in a File
Ever looked at a piece of code and wondered who wrote this and when? Whether you need to debug an issue, review changes, or ask a teammate about their update, Git makes it easy to track down who last modified a specific line in a file.
To do this, run:
git blame filename
What This Does:
-
git blame
displays the author, commit hash, and timestamp for each line in the file. - This helps you identify who changed what and when the change was made.
- Useful for understanding the history of a file and tracking down the reasoning behind changes.
5. Find and Delete Unmerged Branches
Over time, your repository can get cluttered with old branches that were started but never merged. If you want to clean up your local branches while keeping only the merged ones, Git provides a simple way to find and delete unmerged branches.
Run the following command:
git branch --no-merged main | xargs git branch -D
What This Does:
-
git branch --no-merged main
lists all branches that have not been merged intomain
. -
xargs git branch -D
forcefully deletes those branches. - This helps you remove outdated or abandoned branches while ensuring you don’t delete merged work.
How to Check Before Deleting:
If you want to see the unmerged branches first before deleting, run:
git branch --no-merged main
This will list all branches that are not merged into main
. If you're sure you want to delete them, then use the full command:
git branch --no-merged main | xargs git branch -D
Regularly cleaning up unmerged branches keeps your workflow organized and prevents unnecessary clutter in your local repository!
6. Recover a Deleted Branch
Accidentally deleted a branch? Get it back with:
git reflog
git checkout -b branch-name <commit-hash>
What This Does:
-
git reflog
shows a history of all recent Git actions, including commits, checkouts, and branch deletions. - You can use this log to find the last known commit hash of your deleted branch.
- Where
<commit-hash>
is the last known commit of the branch.
7. Save Time with Git Aliases
Are you tired of typing long Git commands repeatedly? Git aliases allow you to create shortcuts for frequently used commands, making your workflow faster and more efficient.
How to Set Up a Git Alias
For example, instead of typing git checkout
, you can create a shorter alias like this:
git config --global alias.co checkout
Now, you can use git co
instead of git checkout
.
You can simply type:
git co branch-name
Why Use Git Aliases?
- Saves time: Reduces typing effort, especially for frequently used commands.
- Improves efficiency: Makes your Git workflow faster and more seamless.
- Customizable: You can create aliases for any Git command to match your personal preferences.
8. List All Remote Branches You’ve Checked Out Locally
When working with Git, you often collaborate with others using remote repositories. If you want to see which remote branches are available, you can use the following command:
git branch -r
What This Does:
-
git branch -r
lists all remote branches that exist in the repository. - It helps track which branches are available on the remote (e.g., GitHub, GitLab, or Bitbucket).
- Useful when you need to check for new branches that have been pushed by teammates.
9. Create a New Branch from a Previous Commit
Need to branch out from an old commit? Use:
git checkout -b new-branch-name <commit-hash>
This creates a new branch from any commit.
Verifying the New Branch
To check that you're now working on the correct commit in the new branch, run:
git log --oneline --graph --decorate
Why Use This Command?
- Isolate new changes: You can work on a feature without modifying the main branch.
- Restore older code: If a bug was introduced recently, you can start from an earlier working version.
- Experiment safely: Try out changes without affecting the current project state.
10. Squash Multiple Commits into One
When working on a feature, you may make several small commits that clutter your Git history. Squashing multiple commits into a single one helps maintain a clean and readable commit history, making it easier to review changes.
To squash commits, use:
git rebase -i HEAD~3
This command starts an interactive rebase for the last 3 commits. You can adjust the number (3) to squash more or fewer commits.
Verifying the Squash
Run:
git log --oneline
You’ll see a cleaner commit history with just one commit instead of three.
11. Delete All Local Branches That Are Merged
Over time, your local repository can become cluttered with old branches that have already been merged. To keep things clean, you can delete all local branches that have been merged into the current branch using:
git branch --merged | grep -v "\*" | xargs -n 1 git branch -d
How It Works
-
git branch --merged
– Lists all local branches that have been merged into the current branch. -
grep -v "\*"
– Excludes the currently checked-out branch (* represents the active branch). -
xargs -n 1 git branch -d
– Deletes each merged branch one by one.
Why Clean Up Merged Branches?
- Keeps your local repository organized by removing unnecessary branches.
- Prevents confusion when switching between active branches.
- Improves performance by reducing clutter in large projects.
12. Restore a Deleted File from Git History
Accidentally deleted an important file? No worries—Git makes it easy to recover files from previous commits.
Basic Recovery (Restore from Last Commit)
If you just deleted a file and haven’t committed the deletion yet, restore it with:
git checkout HEAD -- filename
How It Works
-
HEAD
refers to the latest commit in your current branch. -
-- filename
specifies the file you want to restore. - This brings back the file exactly as it was in the last committed state.
13. Stash Changes Without Losing Them
Sometimes, you're working on a feature but need to switch branches before committing. Instead of losing or committing unfinished work, you can stash your changes and restore them later.
Basic Stashing
To temporarily save (stash) your uncommitted changes, run:
git stash
This moves your modified and staged files into a temporary storage area, allowing you to switch branches freely.
Restoring Stashed Changes
When you're ready to continue working, bring back the stashed changes with:
git stash pop
This restores the last stashed changes and removes them from the stash list.
Viewing Stashed Changes
git stash list
Why Use git stash
?
- Switch branches without committing unfinished work
- Keep your commit history clean by not committing partial changes
- Easily restore work later without losing progress
14. Check What’s Taking Up Space in Your Repo
If your Git repository is getting too large, you might have big files hidden in your commit history. To find the largest files, use:
git rev-list --objects --all | sort -k 2 -r | head -10
What This Command Does
-
git rev-list --objects --all
– Lists all objects (files) in your Git history. -
sort -k 2 -r
– Sorts the files by size in descending order. -
head -10
– Displays the top 10 largest files in your repository.
Why This Is Useful
- Keeps your repository lightweight and fast.
- Prevents unnecessary large files from slowing down cloning and pulling.
- Helps clean up mistakenly committed binaries or datasets.
15. List All Branches Sorted by Last Commit
When working on multiple branches, it’s useful to see which branches have been updated most recently. Instead of checking each one manually, you can sort branches by their last commit date using:
git branch --sort=-committerdate
What This Command Does
-
git branch
– Lists all local branches. -
--sort=-committerdate
– Sorts branches by the most recent commit date, with the newest first (-
means descending order).
Why Use This Command?
- Quickly identify active branches in a project.
- Find outdated or inactive branches that might need cleanup.
- Improve collaboration by checking which branches teammates are actively working on.
16. Search Commit Messages
Need to find a commit with a specific word? Use:
git log --grep="bugfix"
How It Works
-
git log
– Shows commit history. -
--grep="bugfix"
– Filters commits where the message contains the word "bugfix".
Why Use This?
- Quickly locate commits related to specific changes.
- Easier debugging by finding past fixes.
- Helps track feature development by searching for keywords like
"feature"
,"refactor"
, or"update"
.
17. Show a Visual Branch Tree
Understanding how branches and merges interact in Git can be tricky, especially in large projects. You can view a graphical representation of your commit history using:
git log --oneline --graph --all
What This Command Does
-
git log
– Displays commit history. -
--oneline
– Shows each commit as a single line (compact view). -
--graph
– Displays an ASCII graph of branches and merges. -
--all
– Includes commits from all branches, not just the current one.
Why Use This?
- Easily visualize merges and branching in your Git history.
- Quickly identify active branches and their latest commits.
- Understand how features were integrated into the main branch.
18. Change the Last Commit Message
Ever committed a change only to realize you made a typo or forgot to add something to the message? Instead of creating a new commit, you can edit the last commit message using:
git commit --amend -m "New message"
How It Works
-
git commit --amend
– Modifies the most recent commit. -
-m "New message"
– Replaces the previous commit message with "New message".
Why Use This?
- Fix typos or incorrect messages after committing.
- Clarify commit descriptions without adding extra commits.
- Maintain a clean and professional commit history.
19. Clone Only the Latest Commit
When working with large repositories, cloning the entire history can be slow and take up unnecessary space. To speed things up and save bandwidth, you can clone only the latest commit using:
git clone --depth=1 <repo_url>
How It Works
-
git clone
– Clones a repository. -
--depth=1
– Fetches only the most recent commit instead of the entire commit history.
Why Use This?
- Faster cloning – Avoids downloading years of commit history.
- Saves disk space – Only keeps the latest snapshot of the repo.
- Ideal for CI/CD pipelines – Quickly fetch only what’s needed for builds.
🚀 Useful Resources
Category & Topic | Description | Read More |
---|---|---|
⚡ Boost Coding Speed with GitHub Copilot! | Discover how GitHub Copilot can help you write code 4x faster. | Explore Now |
🤖 Start Machine Learning in 10 Minutes! | Quickly set up Jupyter on AWS EC2 and start your ML journey. | Get Started |
🌩️ New to Cloud? Learn cloud computing in a fun and simple way! | Get started with cloud concepts in an engaging and easy-to-understand way. | Start Here |
🚀 Set Up Your Own AI Agent in Minutes! | Clone, run, and deploy your AI agent effortlessly. | Read More |
🚀 Like, share, and support this blog if you found it useful!
Top comments (5)
Helpful post about Git.
Thank you for sharing.😃
Hi WDH
Thank you for your acknowledgement, it means a lot to me. 😍
I will be keep sharing better quality content, stay connected. ⛓️💥
Regards,
Ram
Hi WDH
I would love to hear your thoughts and suggestions about my other articles as well. Please take a look if you get chance.
Thank you,
Ram
It's a useful article, and I appreciate you sharing it.
Hi Wafa Bergaoui ,
Thank you so much for your kind words! I'm glad you found the article helpful. If you enjoyed this one, feel free to check out my other posts as well.
I think you might find those just as useful. Let me know your thoughts, and I’d love to hear what you think!
Regars,
Ram