Git Fundamentals
Git is a distributed version control system that tracks changes to files over time. Unlike centralized version control systems, Git gives every developer a complete copy of the repository, including its full history.
Key Concepts
Repository (Repo): A collection of files and their complete history.
# Initialize a new repository
git init
# Clone an existing repository
git clone https://github.com/username/repository.git
Commit: A snapshot of your files at a specific point in time.
# Stage changes for commit
git add filename.txt
# Stage all changes
git add .
# Commit staged changes
git commit -m "Descriptive message about changes"
Staging Area: A middle ground between your working directory and the repository.
# Check status of working directory and staging area
git status
# See differences between working directory and staging area
git diff
# See differences between staging area and last commit
git diff --staged
Working with Remotes
Remotes are versions of your repository hosted on a server, enabling collaboration with other developers.
GitHub vs GitLab
Both GitHub and GitLab are platforms for hosting Git repositories, but they have some differences:
GitHub:
- World’s largest code hosting platform
- Strong open-source community
- Acquired by Microsoft in 2018
- Features: Actions (CI/CD), Codespaces, Copilot
GitLab:
- Complete DevOps platform
- Available as self-hosted or cloud-hosted
- Integrated CI/CD pipeline
- Features: Built-in issue tracking, wiki, container registry
Managing Remotes
# List all remote repositories
git remote -v
# Add a new remote
git remote add origin https://github.com/username/repository.git
# Change remote URL
git remote set-url origin https://github.com/username/new-repository.git
# Add multiple remotes (e.g., GitHub and GitLab)
git remote add github https://github.com/username/repository.git
git remote add gitlab https://gitlab.com/username/repository.git
Syncing with Remotes
# Download changes from remote without integrating them
git fetch origin
# Download and integrate changes from remote
git pull origin main
# Upload local changes to remote
git push origin main
Best Practices for Remotes
-
Use SSH keys for secure authentication:
# Generate SSH key ssh-keygen -t ed25519 -C "[email protected]" # Add to GitHub/GitLab account cat ~/.ssh/id_ed25519.pub
-
Set up multiple remotes for backup and flexibility:
# Push to multiple remotes git push github main git push gitlab main
-
Use remote tracking branches to simplify commands:
# Set up tracking git branch --set-upstream-to=origin/main main # Now you can use simplified commands git pull git push
-
Keep remote references clean:
# Prune deleted remote branches git fetch --prune