My list of the most useful Git commands
Damian Wróblewski - March 2022
Table of contents
In this post, I've collected my favorite and most useful Git commands and techniques that help me in my daily work. This is an absolute must-have for any young developer who wants to move efficiently in every project.
Let's go!
git log
There are ways to display commits in a more readable way than regular git log
:
Line by line:
git log --oneline
Graph:
git log --oneline --graph --decorate
git revert
If you want to undo changes made in the particular commit but don't want to change the commit history, you can use git revert
. This operation will inverse the changes and create a new revert commit.
git revert <commit>
Not changing the project history makes revert safer option than resetting.
Please note that if your commits are dependent on other commits that have been added, a revert cannot be performed.
git reset
Opposite to revert
, reset
command changes the project history.
If you want to remove specific commit from history but keep the working directory and staging:
git reset --soft <commit>
If you want to remove specific commit from history and files in the stage but keep the working directory:
git reset --soft <commit>
If you want to remove specific commit from history, files in the stage and the working directory:
git reset --hard <commit>
git commit --amend
Adding or removing files from previous commit:
git add .git commit --amend --no-edit
--no-edit
option is responsible for not changing the commit message
Changing the commit message only:
git commit --amend -m "New message"
Both above commands are sufficient if you haven't pushed your changes to the remote repo. Otherwise, you need to overwrite the remote history:
git push --force-with-lease <repository> <branch>
--force-with-lease
is a safer option than --force
which will not overwrite any work on the remote branch if more commits were added. It ensures you do not overwrite someone elses work by force pushing.
Branch removal
To delete particular branch locally:
git branch -d <localBranchName>
To delete specific remote branch
git push origin --delete <remoteBranchName>
git stash
If you want to save your current work without creating additional commit (i.e. you need to change branch) you can add them to stash:
git stash
And when go back to work later:
git stash pop
This is the simplest use of stash. However, you can use stash multiple times with different changes by saving by name:
git stash save <name>
Displaying all of stashed changes:
git stash list
Retrieving specific changes:
git stash apply <index>
Clearing:
git stash clear
Revision
If you want to display changes from specific commit and file:
git show <commit>:path/to/file
That's it. These commands, along with basic git commands, will allow you to efficiently move between branches of even more complex project.
If you found inaccuracies in this post or know other useful git commands, please leave a comment below 😉
Join the discussion