Creating a New Branch and Switching to It and back¶
Creating a new branch in GitHub and switching your local folder to it (and back) involves a few steps using Git commands. Here’s a step-by-step guide:
Creating a New Branch and Switching to It¶
- Open your terminal or command prompt.
- Navigate to your local repository:
cd path/to/your/repository -
Ensure your local repository is up to date:
This fetches updates from the remote repository.git fetch origin -
Create a new branch and switch to it:
This command creates a new branch calledgit checkout -b new-branch-namenew-branch-nameand switches to it immediately. -
Push the new branch to the remote repository:
This pushes your new branch to GitHub and sets up tracking so that futuregit push -u origin new-branch-namegit pushcommands will know which remote branch to push to.
Switching Back to the Main Branch¶
-
Ensure your main branch is up to date:
This fetches updates from the remote repository.git fetch origin -
Switch to the main branch:
Replacegit checkout mainmainwithmasterif your repository usesmasteras the main branch name. -
Pull the latest changes from the remote repository:
Again, replacegit pull origin mainmainwithmasterif necessary. This ensures your local main branch is up to date with the remote repository.
Example Workflow¶
Here’s how the entire workflow might look:
-
Navigate to your local repository:
cd path/to/your/repository -
Fetch updates from the remote repository:
git fetch origin -
Create a new branch and switch to it:
git checkout -b new-feature-branch -
Make your changes and commit them:
git add . git commit -m "Description of your changes" -
Push the new branch to the remote repository:
git push -u origin new-feature-branch -
Switch back to the main branch:
git checkout main -
Pull the latest changes from the remote main branch:
git pull origin main
By following these steps, you can effectively create new branches, switch between branches, and keep your local repository synchronized with the remote repository on GitHub.