Git Installation and Initial Setup

Module 2: Version Control & Containerization

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:

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.

flowchart TD A[Why Git?] --> B[Performance] A --> C[Flexible Workflow] A --> D[Distributed Architecture] A --> E[Massive Adoption] A --> F[Vibrant Ecosystem] style A fill:#f9f9f9,stroke:#333,stroke-width:2px style B fill:#e1f5fe,stroke:#0288d1 style C fill:#e1f5fe,stroke:#0288d1 style D fill:#e1f5fe,stroke:#0288d1 style E fill:#e1f5fe,stroke:#0288d1 style F fill:#e1f5fe,stroke:#0288d1

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)

  1. Visit https://git-scm.com/download/win
  2. The download should start automatically. If not, click the download link for the latest version.
  3. 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
  4. Complete the installation

Option 2: GitHub Desktop

If you prefer a GUI-focused approach:

  1. Download GitHub Desktop from https://desktop.github.com/
  2. Install the application
  3. 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:

  1. Enable WSL through Windows Features or using PowerShell as administrator:
    dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
  2. Install a Linux distribution from the Microsoft Store (e.g., Ubuntu)
  3. Open your Linux distribution and install Git:
    sudo apt update
    sudo apt install git

Verifying Installation on Windows

To confirm Git is installed correctly:

  1. Open Command Prompt or PowerShell
  2. Type git --version
  3. 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:

  1. Open Terminal
  2. Run brew install git

If you don't have Homebrew yet:

  1. Install Homebrew first:
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  2. Then install Git: brew install git

Option 2: Official Git Installer

  1. Visit https://git-scm.com/download/mac
  2. Download the latest installer
  3. Run the installer and follow the prompts

Option 3: Xcode Command Line Tools

If you're a macOS developer, you might already have Git:

  1. Open Terminal
  2. Run git --version
  3. 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:

  1. Open Terminal
  2. Type git --version
  3. 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

  1. Open Terminal
  2. Update package lists: sudo apt update
  3. Install Git: sudo apt install git

Fedora

  1. Open Terminal
  2. Install Git: sudo dnf install git

Arch Linux

  1. Open Terminal
  2. Install Git: sudo pacman -S git

CentOS/RHEL

  1. Open Terminal
  2. Install Git: sudo yum install git

Verifying Installation on Linux

To confirm Git is installed correctly:

  1. Open Terminal
  2. Type git --version
  3. 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:

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.

flowchart TD A[Git Config Levels] --> B[System] A --> C[User/Global] A --> D[Repository] B --> E[/etc/gitconfig] C --> F[~/.gitconfig] D --> G[.git/config] style A fill:#f9f9f9,stroke:#333,stroke-width:2px style B fill:#e8f5e9,stroke:#43a047 style C fill:#e1f5fe,stroke:#0288d1 style D fill:#fff3e0,stroke:#ff9800

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:

  1. Create a file in your home directory (e.g., ~/.gitignore_global)
  2. 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
  3. 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

flowchart TD A[Commit] --> B[Tree] A --> C[Parent Commit] B --> D[Blob: file1.txt] B --> E[Blob: file2.txt] B --> F[Tree: subdirectory] F --> G[Blob: file3.txt] style A fill:#f3e5f5,stroke:#8e24aa style B fill:#e8f5e9,stroke:#43a047 style C fill:#f3e5f5,stroke:#8e24aa style D fill:#e1f5fe,stroke:#0288d1 style E fill:#e1f5fe,stroke:#0288d1 style F fill:#e8f5e9,stroke:#43a047 style G fill:#e1f5fe,stroke:#0288d1

How Git Stores Data

When you initialize a Git repository, Git creates a .git directory containing:

When you commit changes, Git:

  1. Creates blob objects for new/modified file contents
  2. Creates tree objects representing the repository structure
  3. Creates a commit object that points to the tree and has metadata
  4. 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:

flowchart LR A[Working Directory] -->|git add| B[Staging Area] B -->|git commit| C[Git Repository] C -->|git checkout| A style A fill:#e1f5fe,stroke:#0288d1 style B fill:#fff3e0,stroke:#ff9800 style C fill:#e8f5e9,stroke:#43a047

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:

  1. Create a new directory for your project:
    mkdir my-project
    cd my-project
  2. Initialize it as a Git repository:
    git init
  3. 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:

  1. Create a file:
    echo "# My Project" > README.md
  2. Check the status:
    git status
    You should see README.md listed as an untracked file.
  3. Add the file to the staging area:
    git add README.md
  4. Check the status again:
    git status
    Now README.md should be listed under "Changes to be committed".
  5. Commit the staged changes:
    git commit -m "Initial commit with README"
  6. See your commit history:
    git log

Congratulations! You've just created your first Git commit. Let's add more changes:

  1. Edit the README.md file:
    echo "This is a sample project to learn Git" >> README.md
  2. Check the status:
    git status
    README.md should now be listed as modified.
  3. See the specific changes:
    git diff
  4. Stage and commit in one step (for modified files):
    git commit -am "Update README with project description"
  5. View the history again:
    git log
    You should now see two commits.

Cloning an Existing Repository

If you're working with an existing project, you'll typically clone it:

  1. Navigate to the directory where you want to place the project:
    cd ~/projects
  2. Clone the repository (using a sample public repo):
    git clone https://github.com/octocat/Hello-World.git
  3. This creates a new directory named after the repository (Hello-World in this case)
  4. Navigate into the cloned repository:
    cd Hello-World
  5. 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:

Standalone Git Clients

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

GUI Advantages

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:

Git Not Found in Command Line

Problem: The git command isn't recognized after installation.

Solutions:

Line Ending Issues

Problem: Git reports changes to files you haven't modified, often due to line ending conversions.

Solutions:

SSL Certificate Problems

Problem: You see SSL certificate errors when connecting to remote repositories.

Solutions:

Authentication Issues with Remote Repositories

Problem: You're prompted for credentials repeatedly or authentication fails.

Solutions:

Getting Help

Git has excellent built-in help:

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.

Write Good Commit Messages

Commit messages should explain what changes were made and why. A common format is:

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.

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:

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:

  1. Set your name and email
  2. Set your preferred editor
  3. Configure line ending behavior appropriate for your OS
  4. Create at least three useful aliases
  5. Verify your configuration with git config --list

Exercise 2: Repository Creation

Create a new repository and make several commits:

  1. Initialize a new Git repository
  2. Create a README.md file with a project description
  3. Add and commit the README
  4. Create a .gitignore file appropriate for your preferred programming language
  5. Add and commit the .gitignore
  6. Create a simple "Hello, World" program in your language of choice
  7. Add and commit the program
  8. View your commit history with git log

Exercise 3: Repository Exploration

Clone an existing repository and explore its structure:

  1. Clone a public repository (e.g., https://github.com/octocat/Hello-World.git)
  2. Explore its commit history with various git log options
  3. Look at the .git directory structure
  4. Use git show to examine specific commits
  5. Use git blame on a file to see who last modified each line

Further Reading