DEV Community

Catherine
Catherine

Posted on

My personal git cheat sheet

With more than 160 commands available, becoming a git expert takes time. But everyone has a few commands that they use frequently. In this post Iโ€™ll share mine.

I want a clean working directory, but I donโ€™t want to lose my current changes.

# save the current state of the working directory 
git stash

# apply the latest stashed change to your current working tree
git stash pop

# list stashed changes
git stash list
Enter fullscreen mode Exit fullscreen mode

I messed up my last commit message.

# change the latest commit's message 
git commit --amend -m "Fixed message"
Enter fullscreen mode Exit fullscreen mode

I accidentally pushed a file. Now I want to remove it from the remote branch (but not from my local branch).

git rm --cached <file-path>
Enter fullscreen mode Exit fullscreen mode

I made a bunch of changes to a file but I regret it ๐Ÿ˜ฑ. I want to go back to the main branch version.

git checkout main <file-path>
Enter fullscreen mode Exit fullscreen mode

I want to take a commit from one branch and apply it onto mine.

git cherry-pick <commit-hash>
Enter fullscreen mode Exit fullscreen mode

I want my branch to be based off the most recent commit of the main branch.

# 1. Get the latest version of the main branch 
git checkout main
git pull origin

# 2. Checkout your branch
git checkout <my-branch>

# 3. Replay your changes on top of the main branch
git rebase main
Enter fullscreen mode Exit fullscreen mode

I want to squash the commits in my branch to a single commit, before opening a pull request to main.

Before squashing, make sure your development branch is based off the most recent commit of the main branch using rebase. Then:

# 1. Checkout your branch
git checkout <my-branch>

#2 squash commits
git rebase -i main

# The -i does an interactive rebase for you to move and squash commits.
Enter fullscreen mode Exit fullscreen mode

I merged my branch into main but I want to rollback the merge

# 1. Checkout a new branch from the main branch
git checkout -b mybranch-rollback

# 2. Find out the commit hash that merged your branch to develop.
git log 

# 3. Revert the merge commit
git revert -m 1 <commit-hash>

# 4. Push the changes to your new branch
git push origin mybranch-rollback

# 5. Open a pull request to main for your new branch
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
ferluisxd profile image
Luis Vilca

though the third block is what I do using vscode. now I know how to do it with a command! thank you!
Also we basically share the same most used commands, especially the git stash one. I don't know what I would do without that one