DEV Community

loading...
Cover image for Git hacks you should know about

Git hacks you should know about

Ankur Biswas
Someone who thinks he can change the world 👀 👨🏻‍💻
Updated on ・3 min read

In this post, we're going discuss some very useful tricks on Git which literally can save your ass if you screwed up things on Git. Now, without any further ado, let’s get started 🏃🏻‍♂️

Fix last commit message

Have this ever happened to you that you actually want to commit "Final comment" but what you actually typed is "Final commment". Well, it's a shame if other people found out that your comment consists of three m's.
Thankfully there's a fix for this issue.

git commit --amend
Enter fullscreen mode Exit fullscreen mode

Just open your project directory on your terminal and type the above command. This will open up your editor and allow you to make a change to that last commit message. This is a real life saver for me.

Change branch name

Let's suppose that, you want to create a branch named release but somehow you named your branch relaese. Don't panic, there's a solution for this too.

git branch -m relaese release
Enter fullscreen mode Exit fullscreen mode

This will save your butt. But if you have already pushed this branch, then there are a couple of extra steps required. The solution for then will be, you need to delete the old branch from the remote and push up the new one.

git push origin --delete relaese
git push origin release
Enter fullscreen mode Exit fullscreen mode

Added a wrong file in the repo

If you ever commit something in your repo that you shouldn't suppose to then you know how bad the situation is. It could be a rogue ENV file, a build directory, a picture of your dog (suppose 😐) that you accidentally saved to the wrong folder? It’s all fixable.

If you haven't commited it yet then you only have to reset the file.

git reset /assets/img/unknown.jpg
Enter fullscreen mode Exit fullscreen mode

If you have gone committing that change, no need to worry. You just need to run an extra step before:

git reset --soft HEAD~1
git reset /assets/img/unknown.jpg
rm /assets/img/unknown.jpg
git commit
Enter fullscreen mode Exit fullscreen mode

This will undo the commit, remove the image, then add a new commit in its place.

Everything went wrong

This is your ace of spades! When whatever you do go wrong and you have no clue what to do then this is your solution. For example, when you have copy-pasted one too many solutions from Stack Overflow and your repo is in a worse state than it was when you started, then this is your lifesaver.

git reflog
Enter fullscreen mode Exit fullscreen mode

It shows you a list of all the things you've done so far. It then allows you to use Git's time-traveling skills to go back to any point in the past.

When you run this command, it shows something like this:-

4gg9702 (HEAD -> release) HEAD@{0}: Branch: renamed refs/heads/relaese to refs/heads/release
4gg9702 (HEAD -> relaese) HEAD@{2}: checkout: moving from master to release
3c8f619 (master) HEAD@{3}: reset: moving to HEAD~
4gg9702 (HEAD -> feature-branch) HEAD@{4}: commit: Adds the client logo
3c8f619 (master) HEAD@{5}: reset: moving to HEAD~1
48b743e HEAD@{6}: commit: Adds the client logo to the project
3c8f619 (master) HEAD@{7}: reset: moving to HEAD
3c8f619 (master) HEAD@{8}: commit (amend): Added contributing info to the site
egb38b3 HEAD@{9}: reset: moving to HEAD
egb38b3 HEAD@{10}: commit (amend): Added contributing info to the site
811e1c6 HEAD@{11}: commit: Addded contributing info to the site
fgcb806 HEAD@{12}: commit (initial): Initial commit
Enter fullscreen mode Exit fullscreen mode

Remember the left-side column, represents the index. If you want to go back to any point in the history, run the below command, replacing {index} with that reference, e.g. egb38b3.

git reset HEAD@{index}
Enter fullscreen mode Exit fullscreen mode

Have some Git tricks your own? Let me know in the comments below.

Thanks for reading! If you found this helpful, don’t forget to share this with your friends and followers!

Discussion (56)

Collapse
chiangs profile image
Stephen E. Chiang

This is such a time saver...

Switching back and forth between two branches:

git checkout -
Collapse
hyliancoder profile image
ΔNDRΞW

- in general is wonderful. I sometimes forget it exists for git, cd, and others. It makes jumping around directories/branches so much faster.

Collapse
iankurbiswas profile image
Ankur Biswas Author

That's going to be very useful for me. Thanks for sharing this one.

Collapse
kapral18 profile image
Karen Grigoryan

Hey, thanks for sharing.

Couple of notes:

git branch -m relaese release

is a bit confusing i'd suggest changing to:

Rename branch locally

git branch -m old_branch new_branch

Delete the old remote branch

git push origin :old_branch

Push the new branch, set local branch to track the new remote

git push --set-upstream origin new_branch
Collapse
iankurbiswas profile image
Ankur Biswas Author

Thanks for describing in detailed way 😁

Collapse
tcelestino profile image
Tiago Celestino

I always forgot the command to push a delete branch on remote.

Collapse
amcsi profile image
Attila Szeremi⚡ • Edited

For the latter, I like to do:

git push
fuck

:D

Collapse
joehobot profile image
Joe Hobot

be frugal

git add .

Collapse
jess profile image
Jess Lee (she/her)

@maestromac would freak out if he saw me doing this 😝

Thread Thread
maestromac profile image
Mac Siri

It hurts me even when I do it.

Collapse
pierresassoulas profile image
Pierre Sassoulas

If you have untracked files git add . will add them, whereas git add -a will not.

Collapse
joehobot profile image
Joe Hobot

I like to use from time to time, to see where am I fetching/pushing.
Made few times a error where I would copy some dir to another dir and .git would get overwritten :)

git remote -v
(⎈ |k8s-b99)➜  mydir git:(kubernetes) git remote -v
origin  https://github.com/myuser/brooklyn99.git (fetch)
origin  https://github.com/myuser/brooklyn69.git (push)
Collapse
randomnoun7 profile image
Bill Hurt

I also like to use this to see where all my branches are tracking from:

git branch -vv

It tells me which branches currently exist on my machine and which remotes and branches they are tracking. This is useful if you work with a team and you add their remotes to pull their branches down. It can get confusing to keep track of which branches are pointing where so you know where code is going to land when you run git push or where the changes are coming from if you do a git pull.

>git branch -vv
  master                                            d5e2de1 [puppet/master] Merge pull request #297 from clairecadman/sqlserver_doc_edits
  release                                           bddc857 [puppet/release: behind 2] Merge pull request #295 from dylanratcliffe/MODULES-8685-removing-instances-doesnt-work
* tickets/master/MODULES-8610-invoke-agent-job-task bddc857 [bill/tickets/master/MODULES-8610-invoke-agent-job-task] Merge pull request #295 from dylanratcliffe/MODULES-8685-removing-instances-doesnt-work
  tickets/release/MODULES-8721-release-prep-2.4.0   8454979 [bill/tickets/release/MODULES-8721-release-prep-2.4.0] Release Prep 2.4.0

The branch with the asterisk is the one I currently have checked out.

Collapse
iankurbiswas profile image
Ankur Biswas Author

Thanks for sharing.

Collapse
pavelkeyzik profile image
Pavel Keyzik

Wow... git reflog is the best part of this article. Thanks!

Collapse
iankurbiswas profile image
Ankur Biswas Author

👍🏻

Collapse
detunized profile image
Dmitry Yakimenko

What is very important, that these commands rewrite history. And when you rewrite history, you actually create new commits and the old ones stay intact. So if you've pushed already, then after using any of these commands you won't be able to push without --force. And once something is shared it cannot be unshared. Be careful and know what these commands lead to.

I wouldn't call these hacks or tricks, though. Most of these is a regular workflow stuff.

Collapse
capsule profile image
Thibaut Allender

But "hacks" sells more than "commands".

Collapse
gergelypolonkai profile image
Gergely Polonkai • Edited

git commit --amend will add anything in the staging area (or index; the thing files get to when using git add), and let you change the commit message. If you only want to change the commit message leaving the index alone, you can use git commit --amend --only.

When you want to remove a file from the latest commit, after using git reset --soft and co. you can use git commit -C ORIG_HEAD so you don't have to enter the same commit message.

Collapse
iankurbiswas profile image
Ankur Biswas Author

👍🏻

Collapse
sivaraam profile image
Kaartic Sivaraam • Edited

An easier way to remove a file that has been added to the last commit by mistake:

git rm --cached <wrong_file>
git commit --amend

This doesn't delete the file, though. Dropping '--cached' would delete it.

Collapse
iankurbiswas profile image
Ankur Biswas Author

Great 👍🏻

Collapse
elgoorf profile image
Hussein Duvigneau

git bisect but that needs a whole article in itself. If you haven't heard of it, it's a way of quickly pinpointing at which point in history a commit was made, eg. you just noticed a bug, and want to find which code change caused it.

Collapse
iankurbiswas profile image
Ankur Biswas Author

Wow, thanks for sharing 😁

Collapse
wizardrogue profile image
Joseph Angelo Barrozo • Edited

git commit --amend

Never knew that one! Thanks!

Collapse
iankurbiswas profile image
Ankur Biswas Author

👍🏻

Collapse
ltdat287 profile image
dat le tien

Thanks. Very useful.

Collapse
iankurbiswas profile image
Ankur Biswas Author

Glad you liked it 😁

Collapse
vinagreti profile image
Bruno João

git commit --amend can be use to add new modifications to the previous commit.

You can edit a file and mark it to commit

    git add .

and then

    git commit --amend

to insert the modifications in the previous commit.

Collapse
juanvqz profile image
Juan Vasquez
git log --oneline --graph --decorate

Did you use?

Collapse
pierresassoulas profile image
Pierre Sassoulas • Edited

I use aliases for that :

git config --global alias.lga "log --graph --abbrev-commit --pretty=format:'%C(red)%h%Creset -%C(yellow)%d%Creset %s %C(green)(%cr) %C(bold blue)<%an>%Creset' --all"
git config --global alias.lg "log --graph --abbrev-commit --pretty=format:'%C(red)%h%Creset -%C(yellow)%d%Creset %s %C(green)(%cr) %C(bold blue)<%an>%Creset'"

git lga show the whole tree, git lg show just your branch. Can't work without it, I need to know the state of the commit tree in shell very often.

Collapse
iankurbiswas profile image
Ankur Biswas Author

I don't use it in a daily basis. But it's very useful.

Collapse
sivaraam profile image
Kaartic Sivaraam • Edited

There is a short hand for renaming the current branch which isn't mentioned:

git branch -m new_branch

Collapse
iankurbiswas profile image
Ankur Biswas Author

Thanks for sharing 😁

Collapse
kiknaio profile image
George Kiknadze

Extremely useful post, thanks Ankur 👍

Collapse
iankurbiswas profile image
Ankur Biswas Author

Glad you liked it 😁

Collapse
hemanth profile image
hemanth.hm

For the rest: We have git-tips 🔥

Collapse
iankurbiswas profile image
Ankur Biswas Author

Very useful list man. Thanks for sharing 😁

Collapse
analogmemory profile image
Alex

Reflog saved me recently. Such a good one

Collapse
iankurbiswas profile image
Ankur Biswas Author

👍🏻

Collapse
avatarkaleb profile image
Kaleb M

Renaming branches >>>

Thanks for the tips - def will save me some time in the future!!

Collapse
iankurbiswas profile image
Ankur Biswas Author

👍🏻

Collapse
leob profile image
leob

I knew git amend but git reflog that's a cool one ... and git checkout - is a really handy one

Collapse
iankurbiswas profile image
Ankur Biswas Author

👍🏻

Collapse
peterwitham profile image
Peter Witham

This is a great list. I have used amend for the last commit more times than I might be prepared to admit :)

Collapse
iankurbiswas profile image
Ankur Biswas Author

Glad you liked it 😁

Collapse
jecsham profile image
Jecsham

Very useful

Collapse
iankurbiswas profile image
Ankur Biswas Author

Glad you liked it 😁

Collapse
shameemreza profile image
Shameem Reza

Good share @i_ankurbiswas

Collapse
iankurbiswas profile image
Ankur Biswas Author

Glad you liked it 😁

Collapse
price84 profile image
James Price

"Hacks" is pretty inaccurate, more like "commands"

Collapse
iankurbiswas profile image
Ankur Biswas Author

You got me 😄

Collapse
bacchusplateau profile image
Bret Williams

The non-intuitive nature of Git seems to be an opportunity for writing a full-featured GUI on top of the arcane command line wizardry required to do most anything other than a commit.

Collapse
vitalipom profile image
Vitali Pomanitski

Hi Ankur, I wrote a continue tutorial for more advanced topic in a language accessible for beginners, but I can't get featured and reach people to read it. Can you feature it in your one?

Collapse
iankurbiswas profile image
Ankur Biswas Author

Sure, DM me on Twitter