Skip to content

kamipakistan/git_and_github

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 

Repository files navigation

Git and GitHub Guide

Welcome to the Git and GitHub Guide repository! This guide provides a comprehensive introduction to both Git and GitHub—from fundamental concepts and everyday commands to advanced workflows and collaboration techniques.

Table of Contents

  1. Introduction to Git
  2. Getting Started
  3. Basic Git Commands
  4. Branching and Merging
  5. Collaborating on GitHub
  6. Advanced Topics
  7. Resources
  8. Contributing
  9. License

Introduction to Git

Git is a distributed version control system that helps you track changes to your codebase over time. It allows multiple developers to work on the same project simultaneously, keeping a history of changes and enabling efficient collaboration. Whether you're working on personal projects or large-scale software development, understanding Git is crucial for maintaining code quality and managing teamwork.

Getting Started

If you're new to Git and GitHub, this guide will walk you through the initial setup and configuration steps.

Step 1: Installing Git

  1. Download Git: Depending on your operating system, you can download Git from the official website.
  2. Install Git: Run the installer and follow the on-screen instructions.

Step 2: Configuring Git

After installing Git, set your identity—this information will be associated with your commits.

  1. Open Terminal (Linux/macOS) or Git Bash (Windows).
  2. Set your name:
    git config --global user.name "Your Name"
  3. Set your email:
    git config --global user.email "[email protected]"

Step 3: Creating Your First Git Repository Locally

  1. Choose a directory: cd into the folder where you want the repository.
  2. Initialize a repository:
    git init
  3. Peek inside the .git folder:
    ls -a
    Git stores all tracking information in the hidden .git directory.
  4. Check the status:
    git status
  5. Add files to the staging area:
    git add .                 # stage all changes
    git add <file-name>       # stage a single file
  6. Commit your changes:
    git commit -m "Initial commit"

Step 4: Pushing Your Local Repository to GitHub with SSH

Create a Repository on GitHub

  1. Log in to GitHub and click the + sign → New repository.
  2. Give it a name, skip adding a README, .gitignore, or license for now, then click Create repository.

Set Up SSH Keys

  1. Generate a new SSH key pair:
    ssh-keygen -t rsa -b 4096 -C "[email protected]"
  2. Press Enter to accept the default location (or choose a secure passphrase).
  3. Display your public key:
    cat ~/.ssh/id_rsa.pub
  4. Copy the output and add it to GitHub under Settings → SSH and GPG keys → New SSH key.

Link and Push

  1. Add the remote repository using the SSH URL:
    git remote add origin [email protected]:username/repository.git
    git branch -M main
  2. Push your local commits:
    git push origin main

Step 5: Cloning an Existing Repository from GitHub

  1. Copy the repository’s HTTPS or SSH URL from GitHub.
  2. Run:
    git clone <repository-url>
    This downloads the entire repository into a new folder.

Basic Git Commands

git status -s – Short Status

The -s (or --short) flag gives a compact, machine‑readable output.
Left column = staging area status, right column = working tree status.
?? = untracked, M = modified, A = added, etc.

$ git status -s
 M README.md        # modified in working tree, not staged
A  script.py        # added to staging area
?? notes.txt        # untracked

Git file lifecycle

Staging and Unstaging

Stage changes to prepare them for a commit:

git add file.txt          # stage a file
git add .                 # stage everything in the current directory

Unstage a file (remove it from the staging area but keep the changes in the working directory):

git reset HEAD file.txt   # unstage
# or, with the newer syntax
git restore --staged file.txt

Git areas (working, staging, repository)

git log --oneline --graph

View your commit history in a compact, visual graph.

git log --oneline --graph

Example output:

* 3a2b1c0 (HEAD -> main) Fix login bug
* 7d8e9f0 Add user authentication
* 1f2a3b4 Initial commit

With branches:

* 5c6d7e8 (feature) Add search bar
| * 4b5a6c7 (main) Update README
|/
* 3a2b1c0 Base project

git log graph example

git blame – Tracing Changes

git blame shows who last modified each line of a file, the commit hash, and the date.

git blame filename.ext

Example:

^1a2b3c4 (Alice 2024-01-15 10:20:30 +0100  1) # Project setup
2d3e4f5g (Bob   2024-02-01 14:55:00 +0100  2) print("Hello, World!")

Use it to quickly find the author of a bug or understand why a line was introduced. Many IDEs also provide a visual “blame” annotation.

VS Code blame annotation


Branching and Merging

Creating, Switching, and Deleting Branches

  1. Create and switch to a new branch:
    git checkout -b new-feature
    Or with the newer switch command:
    git switch -c new-feature
  2. List branches:
    git branch          # local branches
    git branch -a       # local + remote
  3. Switch between branches:
    git checkout main
    git switch main
  4. Delete a branch after merging (locally):
    git branch -d new-feature      # safe delete – only if merged
    git branch -D new-feature      # force delete
    To delete a remote branch:
    git push origin --delete new-feature

Two branches diverging

Merging Branches: Fast‑Forward vs. 3‑Way Merge

When you merge, Git chooses between a fast‑forward and a 3‑way merge depending on the history.

  • Fast‑forward merge happens when the target branch (main) has no new commits since the feature branch diverged. Git simply moves the main pointer forward.

    git checkout main
    git merge feature-branch

    Before a fast-forward merge

  • 3‑way merge is performed when both branches have diverged. Git uses two branch tips and their common ancestor to create a new merge commit.

    git checkout main
    git merge feature-branch   # results in a merge commit

    You can enforce a merge commit (even if fast‑forward is possible) with:

    git merge --no-ff feature-branch

    A three-way merge commit

Resolving Merge Conflicts

Conflicts occur when the same part of a file is modified in both branches. Git marks the conflicting area:

<<<<<<< HEAD
main branch version
=======
feature branch version
>>>>>>> feature-branch

To resolve:

  1. Edit the file, choose the correct version (or combine both), and remove the conflict markers.
  2. Stage the resolved file:
    git add conflicted-file.txt
  3. Complete the merge:
    git commit
  4. If you want to abort the merge:
    git merge --abort

Collaborating on GitHub

GitHub extends Git with powerful collaboration tools:

  • Forking a repository to create your own copy.
  • Pull Requests (PRs) – propose changes and review code.
  • Issues – track bugs and feature requests.
  • GitHub Actions – automate CI/CD workflows.

The typical flow:

  1. Fork or clone a repository.
  2. Create a feature branch and commit your changes.
  3. Push the branch to GitHub.
  4. Open a Pull Request against the original repository’s main branch.
  5. Discuss, review, and eventually merge.

GitHub collaborative workflow


Advanced Topics

Git Reset, Revert, and Rebase

git reset – Move HEAD and optionally modify staging/working directory

  • git reset --soft <commit>: moves HEAD, keeps staging and working directory.
  • git reset --mixed <commit> (default): moves HEAD, resets staging area, keeps working directory.
  • git reset --hard <commit>: moves HEAD, resets staging and working directory – destructive.

Git reset modes

git revert – Safely undo a commit

Creates a new commit that undoes the changes of a previous one, preserving history.

git revert <commit-hash>

git rebase – Re‑apply commits on top of another base

Unlike merge, rebase rewrites history to create a linear sequence.

git checkout feature
git rebase main

This replays the feature branch commits on top of the latest main, resulting in a clean, straight history. Never rebase commits that have already been pushed to a shared repository unless you’re sure no one else is using them.

Merge vs. rebase comparison

Git Stash – Save Work in Progress

Stashing temporarily shelves modifications, letting you switch contexts without committing half‑done work.

  • Save changes:
    git stash
    Or give it a descriptive message:
    git stash push -m "WIP: new login module"
  • List stashes:
    git stash list
  • Re‑apply the latest stash (keeps the stash):
    git stash apply
  • Apply and remove the stash from the list:
    git stash pop
  • Clear all stashes:
    git stash clear

(Illustrated in the Stashing and Cleaning chapter of the Pro Git book.)

Git Configuration and Line Endings (core.autocrlf)

Git can automatically convert line endings between Windows (CRLF) and Unix (LF). The core.autocrlf setting controls this:

# On Windows – convert CRLF to LF on commit, LF to CRLF on checkout
git config --global core.autocrlf true

# On macOS / Linux – convert CRLF to LF on commit, do not convert on checkout
git config --global core.autocrlf input

# Disable automatic conversion (raw line endings)
git config --global core.autocrlf false

Recommended setup:

  • Windows: git config --global core.autocrlf true
  • macOS / Linux: git config --global core.autocrlf input

Collaboration Workflow: Fetch, Merge, Commit, Push

In a team, you often need to integrate upstream changes before pushing your own work. The classic cycle:

  1. Fetch the latest metadata from the remote without merging:
    git fetch origin
  2. Merge the fetched changes into your local branch:
    git merge origin/main
    Or, as a shortcut, pull (fetch + merge):
    git pull origin main
  3. Resolve conflicts if any, then commit.
  4. Push your updated branch:
    git push origin main

A typical collaborative workflow:

  • git pull --rebase to keep a linear history.
  • Create feature branches, push them, open pull requests.
  • After PR approval, merge on GitHub.
  • Sync your local main with git pull.

Centralized collaboration model


Resources

Contributing

Contributions are highly encouraged! If you spot errors, have suggestions for improvement, or want to add new sections, feel free to open a pull request.

License

This repository is distributed under the MIT License. You are free to use, modify, and distribute the content. Please review the license before using the materials for your own projects.

Happy coding and collaborating!


Disclaimer: This guide is intended for educational purposes. Always refer to the official documentation and additional resources for a comprehensive understanding and best practices.

About

This repository is designed to provide you a comprehensive introduction to both Git and GitHub

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors