What is Git?

Git is a distributed version control system designed to handle everything from small to very large projects with speed and efficiency. It lets multiple developers work on the same project simultaneously without stepping on each other's changes.

Key Benefits:

  • Tracks every change made to your code
  • Supports non-linear development via branches and merges
  • Enables local repositories, allowing offline work
Installing Git

Git can be installed on Linux, macOS, or Windows.

Linux (Debian/Ubuntu):

sudo apt update
sudo apt install git

macOS (Homebrew):

brew install git

Windows: Download the installer from git-scm.com and follow the installation wizard.

Verify Installation:

git --version

This prints the installed Git version, confirming that Git is available.

Git Configuration

Initial Git configuration is crucial for commit attribution and default behavior.

Set Username and Email:

git config --global user.name "Your Name"
git config --global user.email "you@example.com"

Used to tag each commit with author information.

Set Default Editor:

git config --global core.editor nano

This sets the default text editor for writing commit messages.

Enable Colored Output:

git config --global color.ui auto

Improves readability of Git output in the terminal.

Enable Credential Caching (Optional):

git config --global credential.helper cache

Caches your credentials for a limited time.

Check Configuration:

git config --list

Shows all current Git configuration values.

Repositories in Git

Repositories are the core working unit of Git. A Git repository tracks and saves versions of your project.

Initialize a New Repository:

git init

Creates a new .git directory to start version tracking.

Clone an Existing Repository:

git clone https://github.com/user/repo.git

Copies an existing remote repository into a new local directory.

Check Repository Status:

git status

Shows the current state of the working directory and staging area.

Git Workflow Basics

Git's core workflow involves three main states: working directory, staging area, and commit history.

Stage Changes:

git add filename

Moves changes from the working directory to the staging area.

Commit Changes:

git commit -m "Add feature X"

Saves staged changes with a message describing the commit.

Push to Remote:

git push origin main

Uploads commits to a remote repository on the specified branch.

Pull Remote Changes:

git pull origin main

Fetches and merges changes from a remote branch into the current branch.

Check Remote Connection:

git remote -v

Displays the associated remotes.

Viewing History and Changes

Git allows you to inspect historical changes and review diffs.

View Commit Log:

git log

Displays the commit history in chronological order.

Compact Log:

git log --oneline

Shows commit hashes and messages on a single line.

View Differences:

git diff

Compares changes in the working directory against the staging area.

Compare with Last Commit:

git diff HEAD

Shows the changes between the working directory and the latest commit.

View a File's History:

git log filename

Lists all commits that changed a specific file.

Branching and Merging

Branches enable isolated development of features and bug fixes.

Create a Branch:

git branch new-feature

Creates a new branch off the current branch.

Switch Branch:

git checkout new-feature

Moves the HEAD pointer to the specified branch.

Create and Switch Branch:

git checkout -b new-feature

Creates and checks out the new branch in one step.

Merge Branch:

git merge new-feature

Integrates changes from the branch into the current branch.

List All Branches:

git branch

Lists all local branches, marking the current one with an asterisk.

Delete a Branch:

git branch -d branch-name

Deletes a local branch after it has been merged.

Synchronizing with Remote Repositories

Git uses remotes to connect your local repository to a hosted version.

Add a Remote:

git remote add origin https://github.com/user/repo.git

Connects your local repository to a remote one.

Push Changes:

git push origin branch-name

Sends commits to the corresponding branch on the remote.

Pull Changes:

git pull origin branch-name

Fetches and merges remote updates into your current branch.

Fetch Only:

git fetch origin

Downloads remote changes but doesn't merge them.

List Remotes:

git remote -v

Shows the remote URLs associated with your repository.

Undoing Mistakes

Git provides tools to undo, fix, or recover from mistakes.

Unstage a File:

git reset filename

Removes the file from staging.

Amend the Last Commit:

git commit --amend

Modifies the most recent commit.

Revert a Commit:

git revert <commit-hash>

Creates a new commit that undoes changes from a specific commit.

Reset to a Previous Commit:

git reset --hard <commit-hash>

Resets your working directory and history to a specific commit.

Checkout a File from a Commit:

git checkout HEAD~1 filename

Restores the file version from the previous commit.

Using .gitignore

The .gitignore file prevents specified files from being tracked by Git.

Create a .gitignore File:

node_modules/
*.log
.env

Patterns used to exclude directories and file types.

Check Ignored Files:

git status --ignored

Displays all ignored files.

Cleaning Untracked Files

Use Git clean to remove files not under version control.

Dry Run:

git clean -n

Lists untracked files that would be removed.

Remove Untracked Files:

git clean -f

Deletes untracked files.

Remove Untracked Directories:

git clean -fd

Deletes untracked files and directories.

Tags and Releases

Tags are used to mark important points in history.

Create a Tag:

git tag v1.0.0

Tags the current commit.

Create an Annotated Tag:

git tag -a v1.0.0 -m "Initial release"

List Tags:

git tag

Push Tags to Remote:

git push origin --tags
Git Aliases

Aliases save time by creating shortcuts for frequently used commands.

Create Alias:

git config --global alias.st status

Now git st is equivalent to git status.

List All Aliases:

git config --get-regexp alias
Git Internals (Advanced)

Understanding how Git works internally helps advanced users troubleshoot issues.

Git Objects:

  • Blobs: File data
  • Trees: Directory structure
  • Commits: Snapshots

View Git Directory:

ls .git

Inspect Object Types:

git cat-file -t
Common Git Workflows

Different Git workflows support team collaboration and release management.

Centralized Workflow: Single main branch, suitable for small teams.

Feature Branch Workflow: Create a new branch for each feature.

Gitflow Workflow: Structured branching model with develop, release, and hotfix branches.

Forking Workflow: Used in open source; contributors fork a repo and create pull requests.

Troubleshooting and Recovery

Git provides logs and tools to recover lost work.

View Command History:

git reflog

Tracks branch history and HEAD changes

.Recover a Commit:

git checkout <commit-hash>

Fix Merge Conflicts:

Resolve manually, then:

git add .
git commit
Git Hosting Platforms

Platforms offer collaboration and CI/CD tools.

GitHub: Pull requests, Actions, Issues.

GitLab: Built-in CI/CD, free private repos.

Bitbucket: Atlassian integration, pipelines.

Others: SourceForge, Codeberg.

Further Learning Resources