Fixing Git Mistakes
Posted on August 31, 2020 in Git by Matt Jennings
What Happens when you Git Checkout a Branch?
- Change HEAD to point to the new branch
- Copy the commit snapshot to the staging area (also called the index)
- Update the working area with the branch contents
What Happens when you Git Checkout — File?
- Replace the working area copy with the version from the current staging area.
- Overwrite the working area file with the staging area version from the last commit:
git checkout -- <file_path>
Git Clean
- Git clean will clear working area by deleting untracked files.
- WARNING: This operation cannot be undone!
- Use the –dry-run flag to see what would be deleted – see example:
- See what files (NOT directories) would be deleted:
git clean --dry-run
- See what files and directories would be deleted:
git clean -d --dry-run
- See what files (NOT directories) would be deleted:
- Delete a file and directory using git clean:
git clean -d -f
Git Reset
- By default, git performs a:
git reset --mixed
- For commits:
- Move the HEAD pointer, optionally modifies files
- For file paths:
- Does not move the HEAD pointer, modifies files
Git Reset –mixed: Move HEAD Copy Files to Stage
git reset HEAD~
git reset --mixed HEAD~
Git Rest –hard: Move HEAD, Copy Files to Stage and Working
git reset --hard HEAD~
- Warning: This overwrites files and cannot be undone!
Danger: Git Reset Can Change History!
- Warning: Never push changed history to a shared or public repository!
Undo a Git Reset with ORIG_HEAD
In case of an accidental git reset
:
- Git keeps the previous value of HEAD in a variable called:
ORIG_HEAD
- To go back to the way things were:
git reset ORIG_HEAD
Git Revert – The “Safe” Reset
- Git revert creates a new commit that introduces the opposite changes from the specified commit.
- The original commit stays in the repository.
- Revert does not change history.
- Example code:
git revert 2b0b3f2
- A screen will open in Vim and then I’ll save the text (
:wq
), do a commit, and push it to the repo.
Modify a File and then Checkout it Out to a State Just Before it was Modified
echo "Bad Data" > hello.template
git checkout -- hello.template