View a file in a different Git branch without changing branches
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Working with Git, a distributed version control system, involves managing multiple branches that may include various features or experiments within your project. It's commonplace to need to view the contents of a file in a branch other than the one you're currently working on. This can be done without having to switch from your current branch to the target branch, making your workflow more efficient and allowing you to easily compare or reference the content across branches.
Viewing Files Across Branches in Git
When you want to peek at a specific file in a different branch, you have several options:
1. Using git show
The git show command is a powerful tool that can be used to view the contents of a file from any branch without checking that branch out. The syntax is straightforward:
For example, to view the content of example.txt located in a branch named feature-branch, you would run:
This command displays the content of example.txt as it exists on feature-branch, outputting it to your terminal.
2. Using git cat-file
Another approach to view file contents from another branch is using git cat-file. First, find the blob (file) hash associated with the file on the other branch using:
Then, use the blob hash to view the file:
This method is more complex but can be useful in scripts or in more detailed investigative scenarios.
3. Creating a Temporary Branch (alternative method)
If for some reason you prefer not to use the above commands, you can checkout to a new temporary branch, pull the file from the target branch, and then return to your original branch. This method is less efficient but might be used if you need to work extensively with the file's context rather than just view it:
This creates a temporary branch based off the target branch, checks it out, and then deletes the temporary branch after returning to the original branch.
Practical Applications
These capabilities are especially useful in several scenarios:
- Code Review: Quickly checking how a file has been changed in a different branch.
- Comparison: Comparing implementations or solutions across different branches.
- Debugging: Checking if a bug fix or feature exists in another branch without disrupting your current workspace.
Summary Table
| Method | Command | Use Case |
git show | git show <branch_name>:<file_path> | Quick viewing of file contents across branches. |
git cat-file | git ls-tree then git cat-file -p | Detailed investigation or script use. Requires knowing blob hash. |
| Temporary Branch | git checkout -b then git checkout and git branch -D | Extended work or editing on the file from another branch. |

