Practical Scenarios and Techniques
Scenario 1: Fixing a Typo in the Last Commit
Suppose you've just committed a change, but you notice a typo in the commit message. You can use the git commit --amend
command to fix it:
## Fix the typo in the last commit
git commit --amend -m "Fix typo in previous commit"
This will replace the previous commit with a new one that includes the corrected commit message.
Scenario 2: Undoing Multiple Commits Locally
If you've made several commits and want to undo them all before pushing to the remote repository, you can use the git reset
command:
## Undo the last 3 commits, but keep the changes in the working directory
git reset HEAD~3
## Undo the last 3 commits and discard all changes
git reset --hard HEAD~3
The first command will move the branch pointer back by 3 commits, but keep the changes in your working directory. The second command will discard all the changes as well.
Scenario 3: Discarding Specific Changes
If you've made changes to multiple files and only want to discard the changes to a specific file, you can use the git checkout
command:
## Discard changes to a specific file
git checkout -- file1.txt
This will discard all the changes made to file1.txt
and revert it to the state of the last commit.
Scenario 4: Resolving Conflicts When Pushing
If you've made changes to a file that has also been modified on the remote repository, you'll encounter a conflict when trying to push your changes. In this case, you'll need to resolve the conflicts locally, then push the changes:
## Pull the latest changes from the remote
git pull
## Resolve the conflicts in the files
git add .
git commit -m "Resolve conflicts"
## Push the changes to the remote
git push
This process involves pulling the latest changes from the remote, resolving the conflicts in your files, creating a new commit, and then pushing the changes to the remote repository.