乐闻世界logo
搜索文章和话题

How to get just one file from another branch with git

1个答案

1

In Git version control, you may sometimes need to retrieve a specific file from another branch instead of merging all changes from that branch. This can be achieved using the git checkout command. Here are the specific steps:

  1. Navigate to your project's root directory: First, ensure you are in the root directory of your project in the command line.

  2. Check available branches: Use git branch to view all branches and confirm which branch to fetch from.

  3. Checkout the file: Use the command git checkout [branch-name] -- [path-to-file]. Here, [branch-name] is the name of the branch containing the file, and [path-to-file] is the path to the file within the project. For example, to retrieve src/main.py from the feature branch, execute:

    shell
    git checkout feature -- src/main.py

    This command retrieves src/main.py from the feature branch and places it in the same location in your current working directory, overwriting the local src/main.py file.

Example Scenario

Assume you are developing a feature, and your colleague has just completed a login module script login.py on another branch feature-login. This script is critical for your current development. You need this file but do not want to merge all changes from the branch. Execute the following command:

shell
git checkout feature-login -- app/login.py

This retrieves only the app/login.py file from the feature-login branch without affecting other files in your current branch. This is particularly useful for testing or utilizing specific parts of a feature.

By using this approach, you can effectively manage code integration, avoid unnecessary merge conflicts, and ensure modular and reusable code.

2024年6月29日 12:07 回复

你的答案