Introduction to Git
Version control systems track changes to files over time, allowing users to revisit specific versions later. Distributed Version Control Systems (DVCS) like Git, Mercurial, and Bazaar differ from centralized systems by cloning the entire repository locally. This means if a server fails, any local clone can restore the project, as each clone is a complete backup.
Git handles data uniquely compared to other version control tools. Understanding these differences prevents confusion despite similar command structures.
Git Fundamentals
- Snapshot-based storage: Git saves full file snapshots instead of tracking differences between versions.
- Local operations: Most Git commands execute locally, reducing reliance on network connectivity.
- Data integrity: Git uses checksums (SHA-1 hashes) to insure file integrity.
- Append-only model: Git primarily adds data rather than modifying or deleting existing content.
- Three file states: Files in Git exist in one of three states:
- Committed: Safely stored in the local database.
- Modified: Changed but not yet staged for commit.
- Staged: Marked to be encluded in the next commit snapshot.
Git Directory Structure
- Repository Directory: Contains metadata and the object database, the core of Git. Cloning copies this directory.
- Working Directory: A checkout of a specific project version, where files are edited.
- Staging Area: A file (index) listing files to be committed, located in the repository directory.
Basic Git Workflow
- Modify files in the working directory.
- Stage files by adding their snapshots to the staging area.
- Commit updates by permanently storing staged files in the repository.
Generating SSH Keys
To connect to remote repositories, generate an SSH key:
$ ssh-keygen -t rsa -C "user@example.com"
This creates a public key at ~/.ssh/id_rsa.pub.
Creating a New Repository
# Create and enter directory
$ mkdir my-new-repo
$ cd my-new-repo
# Initialize Git repository
$ git init
# Create a file
$ touch README.md
# Add file to staging area
$ git add README.md
# Commit to local repository
$ git commit -m "Initial commit"
# Add remote repository
$ git remote add origin https://github.com/user/my-new-repo.git
# Push to remote (first time with -u)
$ git push -u origin master
Working with an Existing Repository
# Enter repository directory
$ cd existing-repo
# Add remote repository
$ git remote add origin https://github.com/user/existing-repo.git
# Pull latest changes (if histories are unrelated)
$ git pull origin master --allow-unrelated-histories
# Push local changes
$ git push -u origin master