While working on a large Git project, developers create many files for multiple features. A single branch can contain multiple files. Sometimes, they may want to duplicate a single file from one branch to another Git branch. For the corresponding purpose, they utilize the “git checkout” command. This command updates a particular file in a working branch from another branch.
This study will explain the procedure of duplicating a single file from one Git branch to another branch.
How to Copy a Version of a Single File From One Git Branch to Another?
To copy/duplicate a file from one branch to another Git branch, first, switch to the local Git repository. Then, view the list of files in the current working branch and select the file you want to copy to another branch. After that, switch to the target branch and execute the “git checkout <old-branch-name> <file-name>” command. Then, verify the changes in the target branch.
Step 1: Go to Local Directory
First, redirect to the desired local directory using the below-provided command:
Step 2: View List of Files
Then, view the list of available files in the working branch:
According to the below-provided output, the “master” branch contains two files. Choose the file that needs to be copied to another branch. For instance, we have selected the “testFile.txt” file:
Step 3: View Available Branches
Next, check the list of available branches in the current repository:
It can be observed that the working repository contains “alpha” and “master” branches:
Step 4: Switch to Another Branch
Write out the below-provided command and specify the target branch name and switch to it. In our case, “alpha” is the target branch:
Step 5: Check List of Files in Target Branch
Now, view the list of available files in the current branch:
Here, it can be seen that the “alpha” branch contains two further files:
Step 6: Copy File to Target Branch
Then, execute the “git checkout ” command along with the name of a particular file and branch from which you want to copy the file into the target branch:
Step 7: Verify Changes
At last, verify changes by viewing the list of files in the target branch:
The below screenshot indicates that the “testFile.txt” file has been copied from the “master” branch to the “alpha” branch:
We have provided the easiest method to copy a version of a single file from one Git branch to another.
Conclusion
In order to copy/duplicate a single file from one Git branch to another branch, first, redirect to the particular repository. Then, view the list of available files in the working branch and choose the particular file that needs to be copied to another branch. Next, navigate to another branch and run the “git checkout <old-branch-name> <file-name>” command. This study explained the procedure of duplicating a file from one Git branch to another branch.