DEV Community

John Horner
John Horner

Posted on • Updated on

How I figured out what a git pathspec error is, or "well, there's an hour of my life I'm never getting back"

I recently had to get back an earlier version of a specific file from a git repo.

This is simple as far as git is concerned:

git checkout <commit id> <filename>

so if you want to get back the version of file.txt that you had back in commit f6b01b3 you would do

git checkout f6b01b3 file.txt

and that's what you'd get.

But when I did it, I got this:

error: pathspec 'file.txt' did not match any file(s) known to git

and it took quite a while to figure out what was wrong.

What had happened is, a folder in the structure above file.txt had been renamed.

Here's how to reproduce what happened. Let's create a git repo and a file, inside a folder:

john$ git init
Initialized empty Git repository in /Users/john/Library/Scripts/gitexample/.git/
john$ mkdir originalfolder
john$ cd originalfolder/

We make a file, add and commit it. All good.

john$ echo "this is the initial file" > file.txt
john$ git add file.txt 
john$ git commit file.txt -m "initial"
[master (root-commit) f6b01b3] initial
 1 file changed, 1 insertion(+)
 create mode 100644 originalfolder/file.txt

so now, we changed our mind about the name of the folder, we'll rename it (and please note, this is git mv not just mv):

john$ cd ../
john$ git mv originalfolder/ changedfolder
john$ cd changedfolder/
john$ echo "now I've added a line" >> file.txt

we'll commit this new version of the file:

john$ git commit file.txt -m "second"
[master ab9595b] second
 1 file changed, 2 insertions(+)
 create mode 100644 changedfolder/file.txt

no problems there.

Now we want to get back the version of file.txt from the original commit.

john$ git checkout f6b01b3 file.txt 
error: pathspec 'file.txt' did not match any file(s) known to git

git now says it's got a pathspec error and it can't find file.txt, which is right there

Obviously, what's wrong is that when commit f6b01b3 was made, it was in a folder, and that folder no longer exists.

If you want that file back, you'll need to get it back at the original path:

john$ mkdir ../originalfolder
john$ mkdir cd ../originalfolder/
john$ git checkout f6b01b3 file.txt 

this goes through with no problem.

Latest comments (0)