Skip to content

Latest commit

 

History

History
668 lines (535 loc) · 12.4 KB

File metadata and controls

668 lines (535 loc) · 12.4 KB

Complete Git & GitHub Example:



Sign up for GitHub and create an account by providing your email, username, and password.

Create a new repository

  • After signing in, click the “+” icon at the top-right corner and select “New repository.”

  • Enter a repository name — for example:

    • PHPwebsite
    • Javaapp
  • Choose visibility (Public or Private) and click “Create repository.”



Install git:

  sudo dnf install git -y


Setup SSH Authentication:

Generates a new SSH key pair using the Ed25519 algorithm, labeling it with the provided email address.

  ssh-keygen -t ed25519 -C "your_email_ID"

Or

Generates a new SSH key pair using the RSA algorithm, labeling it with the provided email address.

  ssh-keygen -t rsa -b 4096 -C "your_email_ID"

Verify

  la -a
  ls .ssh

Starts the SSH agent in the background and sets up environment variables for SSH authentication.

  eval "$(ssh-agent -s)"

Adds your Ed25519 private SSH key to the SSH agent for authentication.

  ssh-add ~/.ssh/id_ed25519

Displays your public Ed25519 SSH key.

  cat ~/.ssh/id_ed25519.pub

Copy this output to add it to your GitHub>Settings>SSH and GPG keys>New SSH key.

You can test your SSH connection to GitHub; it should return a success message if keys are set up correctly.

  ssh -T git@github.com

Are you sure you want to continue connecting (yes/no/[fingerprint])? yes



Setup HTTPS Authentication

Create a Personal Access Token (PAT) on GitHub:

  • Go to GitHub > Settings > Developer settings > Personal access tokens.
  • Click "Generate new token" (classic is fine for simple use).
  • Give your token a name, select the required scopes (e.g., repo for repository access), and set an expiration date.
  • Click "Generate token" and copy the token. You won’t be able to view it again!

Clone a Repository Using HTTPS

  • Replace <username> and <repo> below:
  git clone https://github.com/<username>/<repo>.git

Clone Example:

  mkdir PHPwebsite
  cd PHPwebsite
  git clone https://github.com/codepoet21/PHPwebsite.git
  ls PHPwebsite
  cd

Global configuration git identity

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

(Optional) Set Up Git Credential Helper:

This securely stores your credentials, so you don’t need to enter your PAT every time.

  • Store temporarily (in memory):
   git config --global credential.helper cache
  • Store permanently (plain text, not recommended for shared systems):
      git config --global credential.helper store

Authenticate with Your PAT When you push, pull, or perform any write operation, Git will prompt for your username and password.


  • Username: Your GitHub username
  • Password: Paste your Personal Access Token (PAT)

Push example:

mkdir JavaApp
cd JavaApp
git init
vim myApp

Write Code and then save and exit.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
  git add .
  git commit -m "Initial commit"
  git remote add origin https://github.com/codepoet21/JavaApp.git
 git push origin master
Username: your-github-username
Password: <paste your personal access token here>

Verify Setup Try pushing/pulling. If successful, your HTTPS authentication is complete!


Troubleshoot:

  1. Pull Remote Changes:

    • git pull origin master
    • If asked, specify merge/rebase:
      • Merge: git pull origin master --no-rebase
      • Rebase: git pull origin master --rebase
      • Fast-forward only: git pull origin master --ff-only
  2. Resolve Conflicts (if any):

    • Edit conflicted files.
    • git add <file>
    • git commit -m "Resolve merge conflict"
  3. Push Again:

    • git push origin master
  • Force Push (Dangerous):
    • Overwrites remote history:
      git push --force origin master
    • Use only if you are sure.


Install & Configure Git

Configure:

git config --global user.name "Your_GitHub_Username"
git config --global user.email "Your_Email_ID"
git config --global core.editor "vim"      # or nano
git config --list

Verify:

git config --list

Additional Global Configuration (Optional)

Change Default Branch Name for New Repositories:

git config --global init.defaultBranch main

Enable Colored Output:

git config --global color.ui auto

Set Up Credential Helper:
- Cache credentials (store in memory for 15 minutes by default):
  ```bash
  git config --global credential.helper cache
  • Store credentials (plaintext, not recommended for shared systems):
    git config --global credential.helper store

Set Merge or Rebase Strategy for Pulls:

  • Always merge:
    git config --global pull.rebase false
  • Always rebase:
    git config --global pull.rebase true


Initialize Local Repository & Add .gitignore: To start tracking your project with Git, create a new directory for your code and initialize a Git repository using git init. This sets up version control and creates a hidden .git folder. It's important to add a .gitignore file, which lists files and directories that Git should not track—such as build artifacts, dependencies, or sensitive data. This keeps your repository clean and secure.

Example: Simple Java App.

mkdir -p ~/JavaApp
cd ~/JavaApp/

Create your Maven project:

mvn archetype:generate -DgroupId=com.example -DartifactId=sample-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

`` cd sample-app


```bash
git init
echo -e "target/\n*.class\n.env\nnode_modules/" > .gitignore

. Stage & Commit Initial Files

echo "# JavaApp" > README.md
vim product-list.js
const products = ["Laptop", "Phone", "Tablet"];
console.log(products);
git status
git add .
git commit -m "chore: initial project setup"
git status

Create Remote Repo on GitHub & Link Local

  • On GitHub: Create JavaApp repo (public, README, default branch: master).
  • Copy SSH link: git@github.com:techgeek68/JavaApp.git
git remote add origin git@github.com:techgeek68/JavaApp.git
git push -u origin master


Create three users, Alice, Bob, and Carol

  • Adds three users (Alice, Bob, Carol) with 'devops' password and gives them sudo privileges.
sudo useradd -m -p $(openssl passwd -1 devops) Alice && \
sudo useradd -m -p $(openssl passwd -1 devops) Bob && \
sudo useradd -m -p $(openssl passwd -1 devops) Carol && \
sudo usermod -aG wheel Alice && \
sudo usermod -aG wheel Bob && \
sudo usermod -aG wheel Carol
cat /etc/passwd

6. Clone Repository (for Bob & Carol)

git clone git clone https://github.com/codepoet21/JavaApp.git
cd JavaApp

7. Standard Git Workflow

Stage & Commit Changes

vim pricefilter
System.out.println("Price Range Filter");
git add pricerangefilter
git commit -m "feat: add price range filter"
git status

Branching

git branch feature/product-filter
git switch feature/product-filter
# or modern: git switch -c feature/product-filter

Edit files, then:

git add product-list.js
git commit -m "feat: add price range filter"
git switch main

Merging

git switch main
git merge feature/product-filter

Remotes

git push origin main
git pull origin main
git remote -v

8. Collaboration: Three Developers

Alice (frontend):

git pull origin main
# Edit product-list.js
git add product-list.js
git commit -m "feat: add price range filter"
git push origin main

Carol (UI):

git fetch origin
# Edit styles.css
git add styles.css
git commit -m "feat: redesign cart UI"
git push origin main

Bob (backend):

git pull origin main
# Edit checkout.php
git add checkout.php
git commit -m "feat: add coupon validation"
git push origin main
# If push fails (Carol pushed first):
git pull --rebase origin main
# Resolve conflicts, then:
git add styles.css
git rebase --continue
git push origin main

9. Common Commands

Status, Diff, Logs

git status
git diff
git diff --staged
git log --oneline --graph --decorate --all

Branch Management

git branch
git branch -vv
git switch -c feature/login
git switch main
git branch -d feature/login

Remote Management

git remote -v
git remote add origin git@github.com:techgeek68/JavaApp.git
git remote remove origin

History & Tagging

git log -- filename
git log --author="Alice"
git tag v1.0.0
git push origin v1.0.0

Stash

git stash push -m "WIP: refactor service"
git stash list
git stash pop

10. Undoing Changes

Edited Not Staged

git restore <file>       # Modern, safer
git checkout -- <file>   # Older syntax

Staged Not Committed

git reset HEAD <file>
git restore --staged <file>
git restore <file>

Already Committed

git reset --soft HEAD~1      # Undo last commit, keep staged
git reset --mixed HEAD~1     # Undo, keep changes in working directory
git reset --hard HEAD~1      # WARNING: Discards changes!
git log                      # Find commit hash
git revert --no-commit <commit_hash>
git commit -m "revert: undo <short-hash> <subject>"

11. Ignore Files (.gitignore)

Example:

# Dependencies
node_modules/
.venv/
venv/
target/
dist/
*.class

# OS
.DS_Store
Thumbs.db

# IDE
.idea/
*.iml
.vscode/

# Logs and env
*.log
.env
.env.*

12. Customizing Git

Configuration

git config --local
git config --global
git config --system
git config --global user.name "techgeek68"
git config --global user.email "pyakurelelx@gmail.com"
git config --global core.editor "vim"
git config --list

Aliases (~/.gitconfig)

[lol]
    log --oneline --graph --decorate --all
[cleanup]
    "!git branch --merged | egrep -v '\\*|main|master' | xargs -r git branch -d"

Hooks (.git/hooks/)

  • pre-commit: run linter/tests
  • pre-push: run smoke tests
  • post-receive: deploy on server

13. Best Practices

  • Descriptive commit messages:
    feat: add user registration
    fix: resolve NPE (#42)
    
  • Use imperative mood, small logical commits
  • Pull before work; push after meaningful commits
  • Strategic branching (main, develop, feature/*, bugfix/*, hotfix/*)
  • Delete merged branches

14. Example: Branch, Edit, Merge

git branch productreview
git switch productreview
echo "<h1>Rate our service</h1>" > userreview
git add userreview
git commit -m "feat(productreview): add user review prompt"
git switch main
git diff main..productreview
git merge productreview
git push origin main

15. Cloning Remote Repo (Various Methods)

git clone https://github.com/techgeek68/JavaApp.git
git clone git@github.com:techgeek68/JavaApp.git
git clone --branch develop https://github.com/techgeek68/JavaApp.git
git clone --depth 1 https://github.com/techgeek68/JavaApp.git

16. Initialize PHP Repo Example

sudo dnf install git -y
mkdir phpproject && cd phpproject
git init
git add .
git commit -m "chore: initial commit"
git remote add origin https://github.com/techgeek68/my-project.git
git push -u origin main

17. Troubleshooting

  • Tracked build artifacts by mistake:

    echo -e "target/\n*.class" >> .gitignore
    git rm -r --cached target
    git commit -m "build: ignore target directory"
  • Push rejected:

    git pull --rebase origin main
    # Resolve conflicts, then:
    git push origin main
  • Wrong email in commits:

    git config --global user.email "correct@example.com"
  • Accidentally committed secrets:

    # Remove secret, use git filter-repo, then force-push (coordinate with team)
    
  • Large repo sluggish:

    git gc --aggressive --prune=now
    git repack -ad

Use this as a reference for any real-world Git & GitHub workflow!