Undoing Unpushed Commits
After making a commit, there may be times when you want to undo or modify the changes before pushing them to a remote repository. Git provides several ways to handle this scenario, depending on your specific needs.
Amending the Last Commit
If you've made a commit and realized that you need to make a small change, you can use the git commit --amend
command to modify the most recent commit. This will allow you to update the commit message, add or remove files, or make other minor changes.
## Make changes to your files
$ git add <modified_files>
$ git commit --amend
After running git commit --amend
, your Git editor will open, allowing you to update the commit message. The changes you've made will be included in the amended commit, and the commit's hash will be updated.
Resetting to a Previous Commit
If you want to undo multiple commits or revert more significant changes, you can use the git reset
command. This command allows you to move the branch pointer to a specific commit, effectively undoing all commits that came after that point.
## Undo the last 3 commits, but keep the changes in your working directory
$ git reset HEAD~3
## Undo the last 3 commits and discard all changes
$ git reset --hard HEAD~3
In the first example, git reset HEAD~3
will move the branch pointer back three commits, but the changes in your working directory will still be present. In the second example, git reset --hard HEAD~3
will move the branch pointer back three commits and discard all the changes in your working directory.
graph LR
A[Commit 1] --> B[Commit 2]
B --> C[Commit 3]
C --> D[Commit 4]
D --> E[Commit 5]
E --> F[Commit 6]
F --> G[Commit 7]
G --> H[Commit 8]
H --> I[Commit 9]
I --> J[Commit 10]
J --> K[Commit 11]
K --> L[Commit 12]
L --> M[Commit 13]
M --> N[Commit 14]
N --> O[Commit 15]
O --> P[Commit 16]
P --> Q[Commit 17]
Q --> R[Commit 18]
R --> S[Commit 19]
S --> T[Commit 20]
subgraph Undo 3 Commits
D --> G
end
subgraph Undo 3 Commits and Discard Changes
D --> A
end
By understanding how to undo unpushed commits, you can effectively manage your project's history and correct any mistakes or unwanted changes before they are shared with others.