Getting Started with GitHub: A Beginner's Guide to Version Control and Collaboration

Creating and Switching Between Branches

Section 2

Branching and Merging: Working on Features Independently

Getting Started with GitHub: A Beginner's Guide to Version Control and CollaborationBranching and Merging: Working on Features Independently

So far, we've been working on a single line of development, often referred to as the 'main' or 'master' branch. This is great for simple projects or when you're just starting out. However, as projects grow and multiple people contribute, working on a single branch can lead to chaos. Imagine trying to fix a bug while simultaneously developing a new feature – changes could easily get mixed up! This is where branches come in. Branches allow you to create isolated lines of development, perfect for working on new features, bug fixes, or experiments without affecting the main project.

Think of branches like copies of your project at a specific point in time. When you create a new branch, you're essentially creating a snapshot of your current code. You can then make changes, add new files, and commit them to this new branch without impacting the original (or 'main') branch. This isolation is the key to productive and organized development.

Let's get hands-on. To create a new branch, you'll use the git branch command followed by the name you want to give your new branch. A common convention is to name branches descriptively, like feature/user-authentication or bugfix/login-error.

git branch feature/add-user-profile

This command creates a new branch named feature/add-user-profile, but you're still currently working on your old branch (likely 'main'). To start working on this new branch, you need to 'switch' to it. We do this with the git checkout command (or git switch in newer Git versions, which we'll cover briefly).

git checkout feature/add-user-profile

After running this command, your working directory will now reflect the state of the feature/add-user-profile branch. Any new commits you make will be added to this branch, leaving your 'main' branch untouched.

To verify which branch you are currently on, you can use the git branch command without any arguments. The current branch will be highlighted with an asterisk (*).

チャプターへ戻る