Git Basics: Unstaging Edits and Reverting a Commit
Before undoing a change, check where it lives: the working file, the staging area, or an existing commit. This exercise preserves your edit when unstaging, then reverses a committed change with a new commit.
Run these commands in Bash with Git 2.28 or newer installed. Each article starts in a fresh temporary repository; no remote account is needed.
git_practice=$(mktemp -d) || exit
cd "$git_practice" || exit
git init -q -b main
git config user.name 'Practice User'
git config user.email 'practice@example.invalid'
git config commit.gpgsign falseThese settings apply only to this repository; signing is disabled for the exercise. Use your own identity in real projects. The temporary files remain after the exercise.
Unstage without losing the edit
printf 'port=8080\n' > app.conf
git add app.conf
git commit -q -m 'Add application config'
printf 'port=9090\n' > app.conf
git add app.conf
git restore --staged -- app.conf
git status --short M app.confThe blank first column means nothing is staged. The second-column M means your working file still has a modification. git restore --staged resets the staging-area copy to HEAD by default, leaving the working file alone.
cat app.confport=9090Be careful with the similar-looking git restore app.conf: without --staged, it replaces the working file from the staging area by default. That can discard uncommitted edits. Git may have no copy from which to recover them.
Reverse a committed change
Now deliberately commit the port change, then undo that commit:
git add app.conf
git commit -q -m 'Change application port'
git revert --no-edit HEAD
cat app.confThe revert prints a commit summary containing a variable ID. The final cat prints:
port=8080git revert adds a new commit that reverses the selected commit’s changes. The original commit stays in history, which makes this useful when other people already have that history.
Start a revert with a clean working tree. In larger histories, overlapping changes can cause conflicts; resolve them before git revert --continue, or use git revert --abort to cancel that in-progress revert. Reverting merge commits requires extra choices and is outside this example.
References
Git restore manual and Git revert manual
Acknowledgements
This post was created with assistance from AI.