Git Commands That Saved My Life At Least Once (edit)

Usage:

git clean -d -f -f
git checkout dev-feat-01
git pull

git checkout dev
git pull

git merge dev-feat-01 --no-ff

1. Get or set user and email variables

git config user.name
git config user.email
git config --system user.email
git config --global user.email
git config --local user.email

2. How to change the author (email) of one or more commits

git commit --amend --no-edit --author="New Name<new_email@free.com>"
git push --force-with-lease

3. Add new changes to the last commit

git commit --amend

4. Remove a commit from the git log

git reset --hard HEAD^

But let’s say your git log is as below:

* 97c8db67 fix: commit 3 is correct as well
* 69e04606 feat: commit 2 is correct
* 9f130ee1 fix: commit 1 needs to be removed

If you need to remove the 9f130ee1 git-sha (“commit 1 needs to be removed”), you could do the interactive rebase:

git rebase -i HEAD~3

Where 3 is the number of commits that you are going to look for before choosing which you would like to remove. Then a text editor will be open with this content:

pick 9f130ee1 fix: commit 1 needs to be removed
pick 69e04606 fix: commit 2 is correct
pick 97c8db67 fix: commit 3 is correct as well

5. Editing an old commit message

git rebase --interactive HEAD~3

6. How to do a rebase from the default branch

git pull --rebase origin main

This will basically:

  1. undo your local commits
  2. pull commits from the remote
  3. add your local commits back

If there are any git conflicts you will be asked to solve them before you push.

7. Reverting local file back to original version in a different branch

git checkout origin/master FILE_PATH_AND_NAME

8. Reverting/Aborting local commit

git reset HEAD~1 (Windows)

git reset HEAD^ (Unix)

9. Showing file remote history

git diff FILE_COMMIT_HASH FILE_PATH

10. Discarding unnecessary  files

git checkout -- .

11. Reverting local commits

git fetch

git reset --hard origin/REMOTE_BRANCH_NAME
git clean -d -f -f

12. Showing committed files that your will push to the remote

git diff --stat --patch origin REMOTE_BRANCH_NAME
git log --oneline 5a984958..49a7891a

References:

http://tugrulaslan.com/list-of-life-saving-git-commands/

https://betterprogramming.pub/7-git-commands-that-saved-my-life-once-or-forty-two-times-c76cc94244de