How to Use Git and GitHub for Version Control: From First Commit to Pull Request
How to Use Git and GitHub for Version Control: From First Commit to Pull Request
Master the fundamental Git workflow to track changes, collaborate with other developers, and manage your codebase securely. This guide takes you from local initialization to a successful production merge.
What You'll Need
- Git installed on your local machine
- A registered GitHub account
- A basic text editor or IDE (e.g., VS Code)
Steps
Step 1: Initialize Your Repository
Navigate to your project folder in the terminal and run 'git init' to create a local repository. This initializes the .git directory, allowing Git to start tracking your file changes.
Step 2: Stage and Commit Changes
Use 'git add .' to move your files to the staging area, preparing them for a snapshot. Execute 'git commit -m "Your descriptive message"' to permanently record these changes in your local version history.
Step 3: Connect to GitHub
Create a new repository on GitHub and copy the remote URL. Link your local project to the cloud by running 'git remote add origin [URL]', ensuring your local environment knows where to push the code.
Step 4: Push Your Initial Code
Upload your local commits to the remote server using 'git push -u origin main'. The '-u' flag sets the default upstream branch, simplifying future pushes to a simple 'git push'.
Step 5: Create a Feature Branch
Avoid working directly on the main branch to keep production code stable. Use 'git checkout -b feature-name' to create and switch to a new branch dedicated to a specific task or bug fix.
Step 6: Sync with the Remote Repository
Before finalizing your work, run 'git pull origin main' while on your feature branch. This integrates the latest changes from your teammates and allows you to resolve any merge conflicts locally.
Step 7: Open a Pull Request (PR)
Push your feature branch to GitHub and navigate to the repository page. Click 'Compare & pull request' to propose merging your changes into the main branch for peer review.
Step 8: Merge and Cleanup
Once the PR is approved and passes all tests, click 'Merge pull request' on GitHub. Delete the remote and local feature branches to keep your workspace organized.
Expert Tips
- Write atomic commits with clear, imperative messages like 'Fix login validation' instead of 'Updates'.
- Use a .gitignore file to prevent sensitive data or node_modules from being uploaded to your public repository.
- Always pull the latest changes from the main branch before starting a new feature to minimize complex merge conflicts.
See also
- Which Programming Language Should I Learn First in 2024?
- Best Practices for Writing Clean Code: A Comprehensive Guide
- How to Optimize Website Performance for Core Web Vitals
- How to Build a Full-Stack Application: The Complete Blueprint