Introduction to Git
In our previous lecture, we explored the evolution of version control systems and their key concepts. Now, we'll focus specifically on Git, the most widely used version control system in the world.
Git was created by Linus Torvalds in 2005 for Linux kernel development. Its design goals included:
- Speed: Perform operations quickly, even with large projects
- Simplicity: Based on a simple internal design
- Strong support for non-linear development: Efficient branching and merging
- Fully distributed: No reliance on a central server
- Ability to handle large projects: Scale to thousands of contributors
Today, Git has become the de facto standard for version control, used by millions of developers across all types of projects. From individual hobbyists to massive enterprises, Git's flexibility and powerful features have made it an essential tool in modern software development.
In this lecture, we'll go step-by-step through the process of installing Git on various operating systems and configuring it for optimal use.
Git Installation by Operating System
Git works on all major operating systems. Let's walk through the installation process for each one.
Installing Git on Windows
Windows users have several options for installing Git:
Option 1: Git for Windows (Recommended)
- Visit https://git-scm.com/download/win
- The download should start automatically. If not, click the download link for the latest version.
- Run the installer and follow these recommended settings:
- When asked about adjusting your PATH environment, select "Git from the command line and also from 3rd-party software"
- For line ending conversions, select "Checkout Windows-style, commit Unix-style line endings"
- For the terminal emulator, choose "Use Windows' default console window" (or MinTTY if you prefer)
- For extra options, ensure "Enable Git Credential Manager" is selected
- For experimental features, the defaults are fine
- Complete the installation
Option 2: GitHub Desktop
If you prefer a GUI-focused approach:
- Download GitHub Desktop from https://desktop.github.com/
- Install the application
- GitHub Desktop includes a bundled version of Git that can also be used from the command line
Option 3: Windows Subsystem for Linux (WSL)
For developers who prefer a Linux environment:
- Enable WSL through Windows Features or using PowerShell as administrator:
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart - Install a Linux distribution from the Microsoft Store (e.g., Ubuntu)
- Open your Linux distribution and install Git:
sudo apt update sudo apt install git
Verifying Installation on Windows
To confirm Git is installed correctly:
- Open Command Prompt or PowerShell
- Type
git --version - You should see a response like
git version 2.40.1.windows.1(version number may vary)
Installing Git on macOS
macOS users have several installation options:
Option 1: Homebrew (Recommended)
If you already have Homebrew installed:
- Open Terminal
- Run
brew install git
If you don't have Homebrew yet:
- Install Homebrew first:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" - Then install Git:
brew install git
Option 2: Official Git Installer
- Visit https://git-scm.com/download/mac
- Download the latest installer
- Run the installer and follow the prompts
Option 3: Xcode Command Line Tools
If you're a macOS developer, you might already have Git:
- Open Terminal
- Run
git --version - If Git is not installed, you'll be prompted to install the Xcode Command Line Tools, which include Git
Verifying Installation on macOS
To confirm Git is installed correctly:
- Open Terminal
- Type
git --version - You should see a response like
git version 2.39.2 (Apple Git-143)(version number may vary)
Installing Git on Linux
Most Linux distributions either come with Git pre-installed or make it easily available through their package managers.
Debian/Ubuntu and Derivatives
- Open Terminal
- Update package lists:
sudo apt update - Install Git:
sudo apt install git
Fedora
- Open Terminal
- Install Git:
sudo dnf install git
Arch Linux
- Open Terminal
- Install Git:
sudo pacman -S git
CentOS/RHEL
- Open Terminal
- Install Git:
sudo yum install git
Verifying Installation on Linux
To confirm Git is installed correctly:
- Open Terminal
- Type
git --version - You should see a response like
git version 2.40.0(version number may vary)
Initial Git Configuration
After installing Git, your first step should be to configure it with your identity and preferences. Git stores these settings in three different places:
- System level: Applies to all users on the system. Located in
/etc/gitconfig - User level: Applies to your user account. Located in
~/.gitconfigor~/.config/git/config - Repository level: Applies only to the specific repository. Located in
.git/configin your repo
Each level overrides the previous one, so repository settings override user settings, which override system settings.
Essential Configuration: User Identity
The first and most important configuration is your user identity. Git embeds this information in every commit you make.
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
Important: Use the email address associated with your GitHub, GitLab, or Bitbucket account if you plan to use these services.
Recommended Configuration Settings
Here are some additional useful configurations that improve your Git experience:
Core Editor
Set your preferred text editor for Git operations like commit messages:
For VSCode:
git config --global core.editor "code --wait"
For Vim:
git config --global core.editor "vim"
For Notepad++ (Windows):
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Default Branch Name
Modern Git conventions use "main" instead of "master" as the default branch name:
git config --global init.defaultBranch main
Line Ending Preferences
Handling line endings consistently across operating systems:
For macOS/Linux:
git config --global core.autocrlf input
For Windows:
git config --global core.autocrlf true
Color UI
Enable colorized output for better readability:
git config --global color.ui auto
Credential Helper
Store credentials to avoid typing passwords repeatedly:
For Windows:
git config --global credential.helper wincred
For macOS:
git config --global credential.helper osxkeychain
For Linux:
git config --global credential.helper cache
git config --global credential.helper 'cache --timeout=3600'
Useful Aliases
Create shortcuts for common commands:
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.lg "log --oneline --graph --decorate"
Viewing Your Configuration
To see all your current settings:
git config --list
To see a specific setting:
git config user.name
To see where a specific setting is defined:
git config --show-origin user.name
Creating a Global .gitignore File
A global gitignore file is useful for excluding files that you never want to track in any Git repository, like operating system files or editor temporary files:
- Create a file in your home directory (e.g.,
~/.gitignore_global) - Add patterns for files you want to ignore:
# OS generated files .DS_Store .DS_Store? ._* .Spotlight-V100 .Trashes ehthumbs.db Thumbs.db # IDE files .idea/ .vscode/ *.sublime-* # Logs and databases *.log *.sqlite # Compiled source *.com *.class *.dll *.exe *.o *.so - Tell Git to use this file:
git config --global core.excludesfile ~/.gitignore_global
Now these files will be ignored in all your repositories without having to add them to each project's .gitignore file.
Git Internals: How Git Works
Understanding Git's internal structure can help you use it more effectively. Unlike other version control systems, Git's approach is unique and powerful.
Git's Data Model
At its core, Git is a content-addressable filesystem. It stores data as objects that are referenced by their SHA-1 hash:
Key Object Types
- Blob: Stores file content (but not its name)
- Tree: Stores directory structure, file names, and references to blobs
- Commit: Points to a tree and contains metadata (author, date, message) and parent commit reference(s)
- Tag: Named reference to a specific commit
How Git Stores Data
When you initialize a Git repository, Git creates a .git directory containing:
- objects/: Contains all Git objects
- refs/: Contains pointers to commit objects (branches, tags)
- HEAD: Points to the current branch
- config: Repository-specific configuration
- index: Staging area information
When you commit changes, Git:
- Creates blob objects for new/modified file contents
- Creates tree objects representing the repository structure
- Creates a commit object that points to the tree and has metadata
- Updates the branch reference to point to the new commit
This content-addressable approach gives Git its speed and integrity checking capabilities. It also means that all history is immutable—you don't change commits; you create new ones.
The Three States of Git
Understanding the three states your files can be in is crucial to working with Git effectively:
- Modified: You've changed the file in your working directory, but haven't staged or committed it yet
- Staged: You've marked a modified file to go into your next commit
- Committed: The data is safely stored in your local database
This three-state system gives you fine-grained control over what changes are included in each commit.
Creating Your First Repository
Now that Git is installed and configured, let's create your first repository and make some commits. There are two ways to start with a Git repository:
Initializing a New Repository
If you're starting a new project from scratch:
- Create a new directory for your project:
mkdir my-project cd my-project - Initialize it as a Git repository:
git init - You should see a message like:
Initialized empty Git repository in /path/to/my-project/.git/
Making Your First Commit
Let's create some files and make our first commit:
- Create a file:
echo "# My Project" > README.md - Check the status:
You should see README.md listed as an untracked file.git status - Add the file to the staging area:
git add README.md - Check the status again:
Now README.md should be listed under "Changes to be committed".git status - Commit the staged changes:
git commit -m "Initial commit with README" - See your commit history:
git log
Congratulations! You've just created your first Git commit. Let's add more changes:
- Edit the README.md file:
echo "This is a sample project to learn Git" >> README.md - Check the status:
README.md should now be listed as modified.git status - See the specific changes:
git diff - Stage and commit in one step (for modified files):
git commit -am "Update README with project description" - View the history again:
You should now see two commits.git log
Cloning an Existing Repository
If you're working with an existing project, you'll typically clone it:
- Navigate to the directory where you want to place the project:
cd ~/projects - Clone the repository (using a sample public repo):
git clone https://github.com/octocat/Hello-World.git - This creates a new directory named after the repository (Hello-World in this case)
- Navigate into the cloned repository:
cd Hello-World - You now have a local copy of the repository with its full history.
Visual Git Clients
While the command line is powerful and essential to understand, many developers also use visual Git clients for certain tasks. Here are some popular options:
Integrated Editor Support
Most modern code editors and IDEs have built-in Git support:
- Visual Studio Code: Excellent Git integration in the sidebar
- IntelliJ IDEA: Comprehensive Git tools in the Version Control panel
- Atom: Git integration via the GitHub panel
- Sublime Text: Git functionality through packages like GitSavvy
Standalone Git Clients
- GitHub Desktop: Simple, focused on GitHub workflows
- GitKraken: Feature-rich with a sleek interface
- Sourcetree: Powerful client from Atlassian
- Fork: Fast and user-friendly
- GitExtensions: Open-source client for Windows
- GitUp: Simple but powerful client for macOS
These tools can be especially helpful for visualizing complex branch structures, reviewing changes, and resolving merge conflicts.
When to Use the Command Line vs. a GUI
Both approaches have their place in a developer's workflow:
Command Line Advantages
- Available on all systems
- Full access to all Git features
- Scriptable for automation
- Faster for many common operations
- Essential knowledge for remote server work
GUI Advantages
- Better visualization of history and branches
- Easier staging of partial files
- More intuitive merge conflict resolution
- Less intimidating for beginners
- Often integrates with hosting platforms
Most experienced developers use both: command line for quick operations and scripts, GUI for visualization and complex merges.
Common Issues and Troubleshooting
Let's address some common issues you might encounter during Git installation and setup:
Permission Denied Errors
Problem: You see "Permission denied" when trying to run Git commands.
Solutions:
- For Linux/macOS, use sudo for installation:
sudo apt install git - Check file permissions in your repository
- On Windows, run Command Prompt or PowerShell as administrator
Git Not Found in Command Line
Problem: The git command isn't recognized after installation.
Solutions:
- Restart your terminal/command prompt
- Verify Git is in your PATH environment variable
- On Windows, if using Git Bash, ensure you're using that terminal
- Re-run the installer and ensure the appropriate PATH option is selected
Line Ending Issues
Problem: Git reports changes to files you haven't modified, often due to line ending conversions.
Solutions:
- Configure core.autocrlf as mentioned earlier
- Add a .gitattributes file to your repository to enforce consistent line endings:
* text=auto - For existing files with line ending issues:
git add --renormalize .
SSL Certificate Problems
Problem: You see SSL certificate errors when connecting to remote repositories.
Solutions:
- Update your Git installation to the latest version
- Check your system date and time are correct
- If necessary (and you understand the security implications), you can disable SSL verification:
git config --global http.sslVerify false
Authentication Issues with Remote Repositories
Problem: You're prompted for credentials repeatedly or authentication fails.
Solutions:
- Set up a credential helper as shown earlier
- For GitHub, consider using a personal access token instead of password
- Set up SSH keys for password-less authentication
Getting Help
Git has excellent built-in help:
- For general help:
git --help - For help on a specific command:
git <command> --help - For a quick reference:
git <command> -h
Best Practices for Starting with Git
As you begin your Git journey, here are some best practices to establish good habits:
Make Atomic Commits
A commit should represent one logical change. This makes it easier to understand, review, and potentially revert changes.
- DO: Make separate commits for separate bug fixes or features
- DON'T: Include unrelated changes in a single commit
Write Good Commit Messages
Commit messages should explain what changes were made and why. A common format is:
- A brief summary line (50 characters or less)
- A blank line
- A more detailed explanation if necessary
Fix input validation in registration form
The email validation regex was incorrectly rejecting valid addresses
with plus signs. Updated to follow RFC 5322 standard.
Commit Early and Often
Make small, frequent commits rather than large, infrequent ones.
- DO: Commit after completing a logical unit of work
- DON'T: Wait until you've made dozens of changes before committing
Use .gitignore Properly
Always set up a .gitignore file at the start of your project to avoid committing files that shouldn't be in version control:
- Build artifacts and output directories
- Dependency directories (e.g., node_modules, vendor)
- Environment and configuration files with secrets
- Operating system and editor temporary files
- Large binary files (unless necessary)
GitHub provides useful template .gitignore files for various languages and frameworks.
Learn from Your History
Regularly explore your Git history to better understand your project's evolution:
git log
git log --graph --oneline --decorate
git blame <file>
git show <commit>
Backup and Synchronize
Even for personal projects, it's a good practice to set up a remote repository (e.g., on GitHub) as a backup and to access your code from multiple devices.
Practice Exercises
Exercise 1: Basic Git Configuration
Configure Git with your personal information and preferences:
- Set your name and email
- Set your preferred editor
- Configure line ending behavior appropriate for your OS
- Create at least three useful aliases
- Verify your configuration with
git config --list
Exercise 2: Repository Creation
Create a new repository and make several commits:
- Initialize a new Git repository
- Create a README.md file with a project description
- Add and commit the README
- Create a .gitignore file appropriate for your preferred programming language
- Add and commit the .gitignore
- Create a simple "Hello, World" program in your language of choice
- Add and commit the program
- View your commit history with
git log
Exercise 3: Repository Exploration
Clone an existing repository and explore its structure:
- Clone a public repository (e.g.,
https://github.com/octocat/Hello-World.git) - Explore its commit history with various
git logoptions - Look at the .git directory structure
- Use
git showto examine specific commits - Use
git blameon a file to see who last modified each line
Further Reading
- Official Git documentation: First-Time Setup
- GitHub Learning Lab - Interactive Git tutorials
- Learn Git Branching - Interactive visual tutorial
- Oh Shit, Git!?! - Common Git mistakes and how to fix them
- Git documentation: gitignore