brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: git restore --source brings back one file from another commit

Git
~/tips/tip-git-restore-source-file-version

git restore --source=HEAD~3 -- src/settings.php

Replaces one file in your working tree with its version from any other commit.

Needing last week’s version of a single file, without moving the whole branch back, is a common situation. Older advice reaches for git checkout, which does too many things. git restore only does this one.

git restore --source=HEAD~3 -- src/settings.php

--source takes a commit, branch or tag. The file in your working tree is replaced by that version and the rest of the repository stays as it is. The manual’s own example is git restore --source master~2 Makefile.

By default only the working tree changes, so you can look at the result, run your tests and commit it, or throw it away with a plain git restore src/settings.php. To put the old version in the index as well, add --staged, or use --staged --worktree for both.

Caveat: it overwrites the file in your working tree without asking. If you have uncommitted edits in that file, they are gone. Run git diff src/settings.php first, or stash.

To see which version you want before you restore, git show HEAD~3:src/settings.php prints the old file without touching anything. The command needs git 2.23 or newer, which is where restore came in.

Further reading: git restore (Git documentation)

More Git tips git show-branch main feature git log --stat -5 git merge --no-ff feature -m "Merge feature" git merge --squash feature git merge --abort All Git tips (144) All topics

Link