I should think that getting a previous version is one of source control's premier features, and should be simple, yet it seems like a treasure hunt finding git solution.
I came across stackoverflow question How can I check out a particular version of one file in Git? . To paraphrase the key thing:
git checkout <commit hash from git log output>
As I expected it to happen, the file in the working directory was replaced/updated with the requested older version, but I lost the later versions in the repository, got a message like "... detached head...".
Any guiding principles here would be appreciated. Thanks.
If you have a special commit like abc123456
and in that commit the file was good, you just need to ...
git checkout abc123456 path/to/file
with this command you will find in stage that version of the file.
You can also use branches:
git checkout old-branch-name path/to/file
When you just use git checkout <somehash>
, then you will get into a detached HEAD. This happens because git checkout
by default just switches branches, and specifying a commit instead of a branch gets you into a “branchless mode” (that's what detached HEAD means).
If you want to get a single file from a different version, you also need to specify the path, ie git checkout <somehash> -- path/to/file
. This will keep everything as it is and just replace the file at path/to/file
with its version from <somehash>
.
So this does overwrite the file. If you want to keep the current version as well, you should rename it first. Otherwise, you can also use a special syntax of git show
for this
git show <somehash>:path/to/file > new_filename.ext
This will essentially get the contents of the file from <somehash>
and print it, so if you pipe it to file, you can extract a file from a different version into a different filename.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.