简体   繁体   中英

Get a file from a git repository at a specific revision number

I have a Git repository in which there files are committed through only one branch. I just use these commands:

git init
git add -A
git commit -m "msg"

I want to get a specific revision of the file. This revision is specified with a number. Currently I use this:

if total number of revisions is 1: git show HEAD:path

and if the revision number is > 1, then: git show HEAD~n:path

However, when I run the code there are some cases in which I get an error saying something like: Invalid object name: HEADn (where n is a number). In subversion I used the svn cat command.

Update

Since I update the repository constantly, I don't want to checkout the repository at a revision if possible.

Other commands equivalent to svn cat :

git cat-file blob ref:path/to/file
git show ref:path/to/some/file.cs.

See Specifying Revisions for replacing ref by (a SHA1, a tag, a branch, ... or, as you are using, <rev>~<n>, eg master~3 )

The main thing to remember about git, is that everything is based around your commits. A commit hash identifies it, and tags, branches are just additional mechanisms to identify a commit, though in the case of a branch its not static, it moves with the HEAD.

so..in order to checkout the file at a particular revision, you just need to find what commit that revision was in, you can look at the history of a particular file with this...

git log --no-merges --oneline -- <path>

or if you are using Git Extensions or other GUI there will be a file history command to show you visually.

Once you know what the commit hash is you can checkout the file at that point using

git checkout <hash>:<path>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM