Lesson 3: Working with Branches and Commits
This lesson covers how to create and switch branches, make commits, push changes, and merge updates in Git.
Step 1: Understanding Branches
A branch in Git is an independent line of development that allows you to work on new features or fixes without affecting the main code.
- The
mainbranch is the default and stable branch. - New branches allow parallel development and prevent incomplete changes from affecting the main project.
- Once a branch is ready, it can be merged back into
main.
Step 2: Creating and Switching Branches
Using GitHub Web
- Open your repository on GitHub.
- Click the "main" dropdown at the top left.
- Type a new branch name (e.g.,
feature-branch). - Click "Create branch".
Using Git (Command Line)
- Check existing branches:
git branch - Create a new branch:
git branch feature-branch - Switch to the new branch:
git checkout feature-branch
Alternatively, create and switch in a single command:
git checkout -b feature-branch
Step 3: Making, Committing, and Pushing Changes
Once you are on a branch, you can start making changes.
-
Modify a file or create a new one:
echo "New feature added" > feature.txt -
Check the repository status:
git status- This shows untracked or modified files.
-
Add the file to staging:
git add feature.txt -
Commit the changes with a descriptive message:
git commit -m "Added feature.txt with a new feature"- Each commit creates a history entry in Git.
-
Push the changes to GitHub:
git push origin feature-branch- This uploads the
feature-branchto GitHub so others can see your changes.
- This uploads the
Step 4: Merging Branches
After testing, merge the changes back into main.
Using GitHub Web (Pull Request)
- Open your repository on GitHub.
- Click "Pull requests" → "New pull request".
- Select
feature-branchand compare it tomain. - Click "Create pull request" and provide a description.
- Once reviewed, click "Merge pull request".
Using Git (Command Line)
- Switch back to the
mainbranch:git checkout main - Merge the feature branch into
main:git merge feature-branch - Push the updated
mainbranch to GitHub:git push origin main
Step 5: Deleting a Branch (After Merging)
Once the branch is merged, it can be deleted to keep the repository clean.
Using GitHub Web
- After merging, click "Delete branch" in the pull request.
Using Git (Command Line)
- Delete the branch locally:
git branch -d feature-branch - Delete the branch on GitHub:
git push origin --delete feature-branch