View a file in a different Git branch without changing branches

GitVersion ControlBranchGit Branch

Git Problem Overview


Is it possible to open a file in a git branch without checking out that branch? How?

Essentially I want to be able to open a file in my github pages branch without switching branches all the time. I don't want to modify it, just want to view it.

Git Solutions


Solution 1 - Git

This should work:

git show branch:file

Where branch can be any ref (branch, tag, HEAD, ...) and file is the full path of the file. To export it you could use

git show branch:file > exported_file

You should also look at VonC's answers to some related questions:

UPDATE 2015-01-19:

Nowadays you can use relative paths with git show a1b35:./file.txt.

Solution 2 - Git

git show somebranch:path/to/your/file

you can also do multiple files and have them concatenated:

git show branchA~10:fileA branchB^^:fileB

You do not have to provide the full path to the file, relative paths are acceptable e.g.:

git show branchA~10:../src/hello.c

If you want to get the file in the local directory (revert just one file) you can checkout:

git checkout somebranch^^^ -- path/to/file

Solution 3 - Git

A simple, newbie friendly way for looking into a file: git gui browser <branch> which lets you explore the contents of any file.

It's also there in the File menu of git gui. Most other -more advanced- GUI wrappers (Qgit, Egit, etc..) offer browsing/opening files as well.

Solution 4 - Git

If you're using Emacs, you can type C-x v ~ or M-x vc-revision-other-window to see a different revision of the file you're currently editing (tags, branches and hashes all work).

Solution 5 - Git

Add the following to your ~/.gitconfig file

[alias]
  cat = "!git show \"$1:$2\" #"

And then try this

git cat BRANCHNAME FILEPATH

Personally I prefer separate parameters without a colon. Why? This choice mirrors the parameters of the checkout command, which I tend to use rather frequently and I find it thus much easier to remember than the bizarro colon-separated parameter of the show command.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSchneemsView Question on Stackoverflow
Solution 1 - GitScolytusView Answer on Stackoverflow
Solution 2 - GitAdam DymitrukView Answer on Stackoverflow
Solution 3 - GitingerView Answer on Stackoverflow
Solution 4 - GitlegosciaView Answer on Stackoverflow
Solution 5 - GitakuhnView Answer on Stackoverflow