This study will demonstrate the process of copying the file from another branch in Git
How to Copy File From Another Branch in Git?
While merging multiple project files, users sometimes encounter issues because of conflict between files, which may cause data loss. To avoid these problems, copy the files or folders from one branch to another. To do so, follow the below-provided procedure.
Step 1: Launch Git Bash
Search and launch the “Git Bash” terminal on your system using the “Startup” menu:
Step 2: Navigate to Specified Directory
Next, move to the specified directory using the “cd” command with the directory path as follow:
Step 3: Check Git Directory Status
Check the Git repository status with the “git status” command:
Step 4: Create New Branch
To create a new branch, run the “git checkout” command:
Here, the “-b” flag is equal to “branch” which is executed to create a new branch named “copy_branch” and switch to it:
Step 5: Create File
Now, create a file in the newly created branch:
Below indicates that we have created a new file named “Linux_hint.txt” and passed the “welcome” string as an argument inside the file:
Step 6: Add File to Git Repository
Run the “git add” command to add the untracked “Linux_hint.txt” file into the Git repository:
Step 7: Commit Changes
Commit the changes into the Git repository with the required message:
Here, “-m” is a flag used to denote the commit message placed in the double quotes:
Step 8: Switch Branch
Run the “git switch” command for switching again to the “master” branch:
As you can see, we have switched back to the “master” branch from the “copy_branch” branch:
Step 9: Copy File
Now, copy the file which is created in the “copy_branch”:
The below-given output indicates that we have successfully copied the file “Linux_hint.txt” from the “copy_branch” named to the “master” branch:
Step 10: Check Git Directory Status
Verify the changes in the Git repository by utilizing the “git status” command:
According to the below output, the “Linux_hint.txt” file is successfully copied into the “master” branch:
That’s all! We have provided the easiest method of copying the file from another branch in Git.
Conclusion
To copy a file from another branch in Git, open up Git Bash and move to the specified directory in which you want to create a file that needs to be copied. Next, run the “$ git status” command to check the repository status and create a new branch using the “$ git checkout -b” command. Next, create a new file and add it to the Git repository. After that, commit changes, switch to the “master” branch, and copy the file with the “$ git checkout” command. This study discussed the procedure of copying the file from another branch in Git.