error: unable to unlink old 'report.txt': Invalid argument on Windows means Git
had to replace a file that another process held open, and Windows would not let it remove
the old copy. Close the program that holds the file, then restore the file with
git restore report.txt so it matches the branch you switched to.
The important part: in this test the switch did not stop. It printed the error, switched
the branch, exited with 0 and left the old content in the working tree, shown as a
modified file. Check git status after you see this message.
The error
> git switch v2 < NUL (run as: cmd /c "git switch v2 < NUL 2>&1")
error: unable to unlink old 'report.txt': Invalid argument
M report.txt
Switched to branch 'v2'
exit=0
> git status --short --branch
## v2
M report.txt
Why it happens
A PowerShell process held report.txt open with
[System.IO.File]::Open(..., "Open", "Read", "Read"): read access, sharing
read only. Switching from main to v2 needed to replace that file,
and the removal of the old copy failed with Invalid argument. Git carried on
with the rest of the switch, so the branch moved while report.txt still held
version one, which git status reports as a local modification.
Outside a test, the holder is whichever program on your machine has the file open.
The command ran with input from NUL, so there was no terminal; in this run
Git asked no question and went straight on.
The fix
> $fs.Close()
...
> git restore report.txt
exit=0
> git status --short --branch
## v2
> Get-Content report.txt
version two
Closing the handle released the file. Running git switch v2 again does not
help, as the test showed: it answered Already on 'v2' and left the file
modified. git restore report.txt wrote the v2 version, and
git status came back clean. If you had real edits in that file, look at
git diff first, because git restore replaces the working copy.
How it was reproduced
Git for Windows 2.45.2.windows.1 on Windows 11, in a Windows PowerShell 5.1 process
started for the test: a new repository with report.txt committed on
main and changed on a branch v2, the file opened from the same
PowerShell process with a FileStream shared for reading only, then
git switch v2 with input from NUL. The stream was closed and
git restore report.txt ran afterwards.
Frequently asked
- How do I fix git error unable to unlink old Invalid argument on Windows?
- Close the program that has the file open, then run git restore on the file so it matches the current branch, and check that git status is clean.
- Did my git checkout or switch finish after unable to unlink old?
- In this test it did: the branch changed and the exit code was 0, but the file kept its old content and showed as modified in git status.
- Why does running git switch again not fix unable to unlink old?
- In this test a second git switch answered Already on the branch and left the file modified. git restore with the file name wrote the correct version.
More decoded errors in the Fixes category.