Master Git: 45 Essential Commands for Everyday Code Merging and Branch Management
This comprehensive guide covers 45 common Git scenarios—including committing, amending, resetting, rebasing, stashing, and branch manipulation—providing clear command examples and step‑by‑step instructions to help developers efficiently manage code changes and resolve typical version‑control challenges.
Popular Past Articles
When Transactional Meets Locks, a Big Pitfall!
I Wrote an Awesome Log Aspect to Shift Blame!
Built a High‑Fidelity B‑Station Clone!
16 Best Practices for Spring Boot in Production
3 Reasons @Transactional Fails and How to Fix Them
Git is a fundamental skill for developers. While GUI tools like Sourcetree simplify merges, mastering the command line is essential for interviews and showcasing expertise.
Below are 45 classic Git scenarios covering commits, amendments, resets, rebases, stashes, branches, merges, and more.
What Did I Just Commit?
To view the latest commit on HEAD after using git commit -a: (main)$ git show Or:
$ git log -n1 -pMy Commit Message Is Wrong
If the commit hasn't been pushed, amend it: $ git commit --amend --only Or in one line: $ git commit --amend --only -m 'new message' If already pushed, you can amend locally and force‑push, though this is discouraged.
Wrong Author/Email in a Commit
For a single commit:
$ git commit --amend --author "New Author <[email protected]>"To rewrite history for all commits, see the git filter-branch guide.
Remove a File from a Commit
Use the following to drop a file from a specific commit:
$ git checkout HEAD^ myfile
$ git add -A
$ git commit --amendDelete My Last Commit
If the commit has been pushed, you can reset and force‑push (use with caution):
$ git reset HEAD^ --hard
$ git push -f [remote] [branch]If not pushed, simply reset: (my-branch*)$ git reset --soft HEAD@{1} Alternatively, use git revert SHA to create a new commit that undoes the changes.
Delete an Arbitrary Commit
Use rebase to drop commits:
$ git rebase --onto SHA1_OF_BAD_COMMIT^ SHA1_OF_BAD_COMMIT
$ git push -f [remote] [branch]Push an Amended Commit – Non‑Fast‑Forward Error
When rebasing or amending creates a new commit, you must force‑push: (my-branch)$ git push origin mybranch -f Generally avoid force‑push; instead create a new commit.
Recover After a Hard Reset
Use the reflog to find lost commits: (main)$ git reflog Then reset to the desired SHA:
(main)$ git reset --hard SHA1234Staging
Add Staged Changes to the Previous Commit
(my-branch*)$ git commit --amendStage Part of a New File
$ git add --patch filename.xShortcut: -p. For a brand‑new file, use: $ git add -N filename.x Then interactively select hunks with e and view staged changes via git diff --cached.
Split Changes Across Two Commits
Use git add -p to interactively select portions for each commit.
Swap Staged and Unstaged Changes
$ git commit -m "WIP"
$ git add .
$ git stash
$ git reset HEAD^
$ git stash pop --index 0Unstaged Changes
Move Unstaged Changes to a New Branch
$ git checkout -b my-branchMove Unstaged Changes to an Existing Branch
$ git stash
$ git checkout my-branch
$ git stash popDiscard Uncommitted Changes
Reset to a previous commit:
# one commit
$ git reset --hard HEAD^
# two commits
$ git reset --hard HEAD^^
# four commits
$ git reset --hard HEAD~4
# or force checkout
$ git checkout -fReset a specific file:
$ git reset filenameDiscard Selected Unstaged Changes
$ git checkout -p
# answer 'y' to drop selected snippetsOr use stash with patch mode:
$ git stash -p
$ git reset --hard
$ git stash popBranches
Wrong Branch Pull
Find the previous HEAD with git reflog and reset:
(main)$ git reflog
ab7555f HEAD@{0}: pull origin wrong-branch: Fast-forward
c5bc55a HEAD@{1}: checkout: checkout message goes here
(main)$ git reset --hard c5bc55aDiscard Local Commits to Match Remote
(my-branch)$ git status
# shows ahead by N commits
(main)$ git reset --hard origin/my-branchCommit to Wrong Branch (main) Instead of New Branch
(main)$ git branch my-branch
(main)$ git reset --hard HEAD^
(main)$ git checkout my-branchKeep a Whole File from Another Ref
(develop)$ git checkout solution -- file1.txtSplit Commits Across Different Branches
Reset main to a clean commit, then cherry‑pick specific commits onto new branches:
(main)$ git reset --hard a13b85e
(main)$ git checkout -b 21
(21)$ git cherry-pick e3851e8
(main)$ git checkout -b 14
(14)$ git cherry-pick 5ea5173Delete a Remote Branch
(main)$ git push origin --delete my-branch
# or
(main)$ git push origin :my-branchDelete a Local Branch
(main)$ git branch -D my-branchCheckout a Remote Branch Someone Else Is Working On
(main)$ git fetch --all
(main)$ git checkout --track origin/davesRebasing and Merging
Undo a Rebase/Merge
(my-branch)$ git reset --hard ORIG_HEADRebase Without Force‑Pushing
(main)$ git checkout my-branch
(my-branch)$ git rebase -i main
(my-branch)$ git checkout main
(main)$ git merge --ff-only my-branchCombine Multiple Commits
Soft‑reset to the base branch and recommit:
(my-branch)$ git reset --soft main
(my-branch)$ git commit -am "New awesome feature"Or use interactive rebase to squash/fixup commits.
Safe Merge Strategies
(main)$ git merge --no-ff --no-commit my-branchMerge a Branch as a Single Commit
(main)$ git merge --squash my-branchCombine Unpushed Commits Only
(main)$ git rebase -i @{u}Check If All Commits on a Branch Are Merged
(main)$ git log --graph --left-right --cherry-pick --oneline HEAD...feature/branchInteractive Rebase Troubleshooting
If the editor shows noop, the branches share the same tip; try rebasing onto an earlier commit.
For conflicts, resolve them, then continue:
(my-branch)$ git add <file>
(my-branch)$ git rebase --continueTo abort a rebase:
(my-branch)$ git rebase --abortStash
Stash All Changes
$ git stashStash Specific Files
$ git stash push path/to/file1.ext path/to/file2.extStash with a Message
$ git stash save "my message"
# or
$ git stash push -m "my message"Apply a Specific Stash
$ git stash list
$ git stash apply "stash@{n}"Stash While Keeping Unstaged Changes
$ git stash create
$ git stash store -m "commit-message" CREATED_SHA1Miscellaneous
Clone All Submodules
$ git clone --recursive git://github.com/foo/bar.git
# or after cloning
$ git submodule update --init --recursiveDelete a Tag
$ git tag -d <tag_name>
$ git push <remote> :refs/tags/<tag_name>Recover a Deleted Tag
$ git fsck --unreachable | grep tag
# note the hash and then
$ git update-ref refs/tags/<tag_name> <hash>Recover a Deleted Patch
If a pull‑request author removed their fork, manually copy the changes into a new branch, commit, adjust the author, and open a new pull request.
Rename a File’s Case Only
(main)$ git mv --force myfile MyFileRemove a File from Git but Keep It Locally
(main)$ git rm --cached log.txtConfigure Git Aliases
Typical aliases in ~/.gitconfig:
[alias]
a = add
amend = commit --amend
c = commit
co = checkout
d = diff
ds = diff --staged
f = fetch
loll = log --graph --decorate --pretty=oneline --abbrev-commit
m = merge
s = status
unpushed = log @{u}
zap = fetch -pCache Repository Credentials
$ git config --global credential.helper cache
# Set timeout (seconds)
$ git config --global credential.helper 'cache --timeout=3600'Recover Lost Work with Reflog
Reflog records every change to HEAD even if not referenced by a branch or tag:
(main)$ git reflog
0a2e358 HEAD@{0}: reset: moving to HEAD~2
0254ea7 HEAD@{1}: checkout: moving from 2.2 to main
c10f740 HEAD@{2}: checkout: moving from main to 2.2Use the recorded SHA to reset back:
$ git reset --hard 0254ea7Author: 小富 Source: https://blog.csdn.net/xinzhifu1/article/details/123271097
Popular Past Articles
1、 I Reproduced a Spring Vulnerability – Beware!
2、 Distributed Locks: Redis vs Zookeeper?
3、 8 Must‑Read Sites for Late‑Night Browsing
4、 Is There a Length Limit for Strings?
5、 14 Companies’ Layoff Lists (Jan‑Feb)
6、 8 Pitfalls of Using Redis for Distributed Locks
7、 Uninstall This IDEA Plugin Immediately!
8、 What Does Thread.sleep(0) Actually Do?
9、 Why Not Use try‑catch for Exception Handling?
10、 Why MySQL Shouldn’t Use UUID as Primary Key
Image
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
