Skip to content
Git Basics: Saving and Applying a Patch File

Git Basics: Saving and Applying a Patch File

October 10, 2026

A patch file stores a textual diff that you can inspect and apply later. This example saves an unstaged edit, returns the file to its committed state, then applies the saved patch.

Run these commands in Bash with Git 2.28 or newer installed. Start a fresh temporary repository for this article:

git_practice=$(mktemp -d) || exit
mkdir "$git_practice/repository"
cd "$git_practice/repository" || exit
git init -q -b main
git config user.name 'Practice User'
git config user.email 'practice@example.invalid'
git config commit.gpgsign false

The identity and signing settings apply only to this repository. Use your own identity in real projects. The temporary files remain afterward. Examples assume default Git settings; if a pager opens, press q to leave it.

Save an edit as a patch

printf 'port=8080
' > app.conf
git add app.conf
git commit -q -m 'Add application config'
printf 'port=9090
' > app.conf
git diff > ../port-change.patch
git diff --stat
 app.conf | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

The patch is outside the repository, so it will not be accidentally staged here. Plain git diff includes unstaged changes to tracked files. It does not include untracked files or changes already staged; use git diff --cached for staged changes. For binary changes, use an appropriate binary patch workflow instead of this text-only example.

Inspect before restoring

grep '^[+-]port=' ../port-change.patch
-port=8080
+port=9090

This shows the changed lines. In real work, read the whole patch before applying it; patches can modify code or scripts you will later execute.

The next command discards the unstaged edit in app.conf, restoring it from the index. Run it only in this temporary exercise after checking the patch. Git cannot recover arbitrary discarded working-tree edits that were never recorded.

git restore app.conf
cat app.conf
git apply --check ../port-change.patch
port=8080

--check tests whether the patch applies without changing any files. Success is silent. If the target file has changed, the check may fail; inspect the mismatch rather than forcing the patch.

Apply and review

git apply ../port-change.patch
cat app.conf
git status --short
port=9090
 M app.conf

git apply changes working-tree files by default. It does not stage them or create a commit. Review and test the result before using git add and git commit. A plain diff also does not preserve an author’s identity or commit message; git format-patch and git am serve that separate workflow.

References

git-diff manual, git-apply manual, git-restore manual

Acknowledgements

This post was created with assistance from AI.

Last updated on