DEV Community

Cover image for Life-saving git commands

Life-saving git commands

Abhishek S. Sharma on July 18, 2020

1. Life-Saving git tips We have two branches (dev and master) and one file in both branches with one commit for implementation of below ...
Collapse
 
jingxue profile image
Jing Xue

4 is not correct. git commit --amend will try to amend the last commit by adding not-to-be-commit.txt to it. So after :wq you will have effectively squashed not-to-be-commit.txt to the last commit on the branch.

To undo a file accidentally added to the index, simply do git restore --staged not-to-be-commit.txt.

Collapse
 
imabtiwari profile image
Abhishek S. Sharma • Edited

There are many ways to do that you can simply write this :

git rm --cached not-to-be-commit.txt

And Please try this one too (The —amend command), it always works for me. I practiced each and every command and wrote here. Let me know if you have other suggestions. Thanks !!

Collapse
 
jingxue profile image
Jing Xue

I use --amend everyday to squash changes into the last commit. If you look into the last commit on the branch after doing git --amend, you'll see that the file you didn't want to add has become part of the commit. :-)

git rm --cached would indeed work too, however it is the "old way" of doing it. If you have a recent git version, when you run git status, it would suggest to use git restore --staged.

Collapse
 
octaneinteractive profile image
Wayne Smallman

A personal favourite is:

git reset HEAD^

… to undo the last commit, or:

git reset HEAD~n

… where n is the number of commits to undo.

Collapse
 
octaneinteractive profile image
Wayne Smallman

It becomes a bit problematic if you've done a push beforehand!

Collapse
 
kartik_saxena14 profile image
Kartik Saxena

Useful Content
Keep it up

Collapse
 
itdeepa profile image
Deepa khandelwal

Very useful content n kudos to you!!

Collapse
 
aayushidroid profile image
Aayushi Sharma

Thanks Abhishek for your informative articles. Git is always life saver for a developer.

Collapse
 
indrakuma_r profile image
Indra Kumar

Great! Sir

Collapse
 
himmatfidelesys profile image
himmat-fidelesys

Great sir ....

Collapse
 
dingdingdong profile image
The D

Thank you so much. I wanted to learn this especially when I am editing remote code using terminal.