After completing some code changes on a branch, you might need to apply those changes to another branch. Here are some common methods to achieve this using Git:
1. Using git checkout and git commit
First, ensure all changes on the current branch have been committed. Then, follow these steps to move changes to another branch:
bash# Switch to the target branch git checkout target-branch # Merge changes from the source branch git merge source-branch
Example
Suppose I made some changes on the feature branch and want to apply those changes to the main branch. I would do the following:
bash# Commit changes on feature branch git add . git commit -m "Completed feature development" # Switch to main branch git checkout main # Merge feature branch changes into main branch git merge feature
2. Using git cherry-pick
If you only want to apply specific commits rather than all changes from a branch, you can use the git cherry-pick command. This command selectively applies one or more specific commits from another branch to the current branch.
bash# Switch to the target branch git checkout target-branch # Apply specific commits git cherry-pick commit-id
Example
Suppose I have multiple commits on the feature branch, but I only want to apply the latest commit to the main branch.
bash# Switch to main branch git checkout main # Apply the latest commit from feature branch git cherry-pick latest-commit-id
3. Using git rebase
If you want to rebase changes from one branch onto another branch, you can use the git rebase command. This is typically used to keep a branch synchronized with the main branch.
bash# Switch to the branch to update git checkout target-branch # Rebase onto another branch (e.g., main branch) git rebase source-branch
Example
Suppose the feature branch is behind the main branch, and I want to update the feature branch to include the latest changes from main:
bash# Switch to feature branch git checkout feature # Rebase feature branch onto main branch git rebase main
The above are some common methods to apply changes from one branch to another in Git. Which method to use depends on the specific development workflow and requirements.