Skip to content

potatoscript/git

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 

Repository files navigation

GIT Cheat Sheets & Complete Tutorial Menu

Title Remark/Code
Introduction to Git What is Git? Why use Git? Difference between Git and GitHub
Installation Install Git on Windows, macOS, Linux
Git Basics Understanding repositories, commits, branches, remotes
Setting Up Git Configure username, email, aliases using git config
Alias Setup Create shortcuts for long Git commands
Basic Git Commands init status commit log add diff checkout reset
Creating a Repository Initialize and configure a new repository
Working with Files Adding, modifying, deleting files in Git
.bashrc file Customize Git command aliases
.gitignore file Ignore files and directories from tracking
Editing Files Read/edit files using cat vim nano code
Staging and Committing add commit commit --amend
Branching & Merging Managing branches and merging changes
Creating & Switching Branches branch checkout switch
Merging Branches merge rebase cherry-pick
Rebasing rebase rebase --interactive
Squashing Commits rebase -i to combine multiple commits
Cherry-Picking Apply specific commits from another branch
Working with Remote Repositories Connecting local Git to remote repositories
Adding a Remote Repository git remote add origin
Cloning a Repository git clone to copy a remote repository
Fetching, Pulling & Pushing git fetch git pull git push
Moving Local Repo to Remote git remote add git push -u origin
Undoing & Resetting Changes Fix mistakes and revert changes
Undoing Changes reset restore checkout reflog
Unstaging Files restore reset HEAD clean
Reverting Commits revert commit --amend
Reset, Checkout, Restore checkout reset restore
Restoring a File to an Earlier Version restore checkout reset
Viewing and Comparing Changes Track modifications in your project
Viewing Staged & Unstaged Changes diff diff --staged difftool
Comparing Commits diff log --oneline
Viewing the History log log --graph
Viewing a Commit show ls-tree
Handling Merge Conflicts Resolve issues when merging branches
Troubleshooting Merge Conflicts Using merge rebase conflict resolution
Working with Stashes stash stash pop stash apply stash drop
Git Tagging & Releases Manage software versions using tags
Tagging Commits git tag git tag -a git tag -d
Working with Feature Branches checkout -b merge rebase
Advanced Git Features Powerful Git tools for workflow
Git Hooks Automate tasks with pre/post-commit hooks
Git Submodules submodule add submodule update
Interactive Rebase rebase -i to modify commit history
Bisecting git bisect for debugging commits
Git Collaboration Best practices for working with teams
Forking and Pull Requests Fork, clone, modify, submit PRs
Code Reviews with GitHub Using GitHub for reviews and approvals
Security and Best Practices Keep your codebase secure
Signing Commits Use GPG to sign Git commits
Git Best Practices Writing good commit messages, branch strategies
Git for DevOps & Automation Using Git in CI/CD pipelines
Git in CI/CD Pipelines Automate testing and deployments
Git Internals & Performance Deep dive into Git
Understanding Git Internals Objects, trees, and commits
Optimizing Git Performance gc fsck repack to clean and speed up
Git Wiki Repository Documenting with Git
Wiki Repository Manage GitHub Wiki repositories

Comprehensive Git Tutorial

Introduction

Git is an essential tool for version control, enabling efficient collaboration and code management. This tutorial provides a detailed walkthrough of key Git commands, including rebasing, amending commits, cleaning up repositories, and force pushing changes.


1. Configuring a Safe Directory in Git

To ensure Git recognizes your working directory as safe and prevents unnecessary warnings, execute the following command:

git config --global --add safe.directory "*"

2. Rebasing in Git: Editing Commits

Rebasing allows you to modify commit history. Follow these steps to edit commits:

  1. Initiate an Interactive Rebase:

    git rebase -i --root
  2. Modify Commit Messages:

    • The command opens an interactive rebase interface.
    • Change pick to reword for the commit you wish to edit.
    reword <commit-hash> <commit-message>
  3. Save and Exit:

    • Press ESC, then type :wq and press Enter to save changes.
  4. Continue the Rebase Process:

    git rebase --continue
  5. Force Push Updated Commits:

    git push origin <branch-name> --force

(Replace <branch-name> with your actual branch name.)


3. Resetting and Amending Commits

To reset or modify commit messages, follow these steps:

  1. Soft Reset to a Previous Commit:

    git reset --soft <commit-hash>
  2. Amend a Commit Message:

    git commit --amend -m "Updated commit message"
  3. Push Amended Commit:

    git push origin <branch-name> --force

4. Resolving Missing Objects in Git

If Git reports missing objects, perform the following steps:

  1. Check Repository Integrity:

    git fsck --full
  2. Optimize and Cleanup the Repository:

    git gc --prune=now

5. Cleaning and Optimizing a Git Repository

To maintain repository efficiency:

  1. Remove Old References:

    git reflog expire --expire=now --all
  2. Run Garbage Collection:

    git gc --prune=now
  3. Repack the Repository:

    git repack -A -d
  4. Validate Repository Health:

    git fsck --full

6. Merging Unrelated Histories

When pulling changes from different repositories, you may need to allow unrelated histories:

git pull origin main --allow-unrelated-histories

Interactive Rebase: Editing Commit Messages

To modify commit messages in Git using interactive rebase, follow these steps:

  1. Start the Rebase: Open your commit history in interactive mode:

    git rebase -i --root
  2. Enter Insert Mode: Git will open the commit history in your configured text editor. To make edits, press i to enter INSERT mode.

  3. Change pick to reword: Locate the commit you want to edit and replace pick with reword. For example:

    reword <commit-hash> <commit-message>

    This allows you to modify the commit message.

  4. Exit Insert Mode: Once you've made the necessary changes, press the ESC key to exit INSERT mode.

  5. Save and Quit: Save the changes and close the editor by typing:

    :wq

    Then press Enter.

  6. Continue the Rebase: After saving, Git will prompt you to confirm the rebase. To proceed, run:

    git rebase --continue

This process ensures that your commit history remains structured while allowing you to refine commit messages effectively.


Summary of Key Commands

Task Command
Set safe directory git config --global --add safe.directory "*"
Start interactive rebase git rebase -i --root
Amend commit message git commit --amend -m "Updated message"
Force push changes git push origin <branch-name> --force
Check for missing objects git fsck --full
Run garbage collection git gc --prune=now
Remove old references git reflog expire --expire=now --all
Merge unrelated histories git pull origin main --allow-unrelated-histories

  • Long-Running Branches (main, master, develop, staging, production branch )

    • exist through the complete lifetime of the project
    • often they mirror "stages" in your dev life cycle.
  • Short-lived branches (feature branch)

    • for new features, bug fixes, refactorings, experiments...
    • will be deleted after integration (merge/rebase)
  • Two Branching Strategies

    1. GitHub Flow - very simple, very lean: only one long-running branch(main or master) + feature branches.
    2. GitFlow - more structure, more rules...
      • long-running : main + develop
      • short-lived : features, releases, hotfixes.

Title Remark/code
Installation Setup and Configuration GIT config
Alias Setup shortcut for those long long commands
Basic Operation init status commit cat list ls echo touch rm
Create Repository https://stackoverflow.com/questions/20325089/hosting-a-git-server-on-localhost
.bashrc file Create .bashrc file to store your own alias
.gitignore file https://www.codegrepper.com/code-examples/csharp/aspnet+core+gitignore
Editing File read file cat and edit file vim or code
Move your project to Remote remote push
Restoring a File to an Earlier Version restore
Trouble Shooting Conflict stash
Unstaging Files restore clean
Viewing Staged & Unstaged Changes diff --staged difftool
Viewing the History log
Viewing a Commit show ls-tree
Workflow basic Clone Pull Push from Remote and create branch branch merge
Workflow with feature branch using tag
Wiki Repository
Clone Repository clone all your GitHub repositories and their corresponding wiki repositories at once

home

Create Branch
Pull Requests Communicating about and reviewing code
Merge
Merge Conflicts When Integrating commits from different Sources
Rebase Integrating with rebase -> a straight line of commits
Cherry-Picking Integrating Single, Specific Commits

home

Branch

  • Create branch
git branch test
git checkout test
  • set your remote origin repository
git remote add origin /C/Apache24/htdocs/potatoscript.git
  • make some change and commit and push it into the remote branch
  • the --set-upstream allows you to set the default remote branch for your current local branch
  • By default, every pull command sets the master as your default remote branch
git push --set-upstream origin test

Pull Requests

  • without a Pull Request you would jump right to merging your code.
  • Invites reviewers to provide feedback before merging
  • Contributing code to other repositories that you don't have right access
  • normally we will Fork the other people origin repository that you don't have the right to make changes
    and clone it into your local repository to do editing.

home

Merge

  • Merging Branches = Integrating one Branch into Another
  • To merge branches locally, use git checkoutto switch to the branch you want to merge into.
  • Next, use git mergeand specify the name of the other branch to bring into this branch.
git checkout main
git merge feature/feature1

home

Merge Conflicts

  • When contradictory changes happen
  • To solve the conflicts use
    • git rebase, git pull, git cherry-pick, git stash apply
    • use the git mergetool like www.git-tower.com

home

Rebase

  • Interactive Rebase
- Change a commit's message
- delete commits
- reorder commits
- combine multiple commits into one
- edit/ssplit an existing commits into multiple new ones.
- Do NOT use Rebase on commits that you have already pushed/shared on a remote repository!!!
- Instead, use it for cleaning up your local commit history before merging it into a shared team branch.
  • the mechanism of git rebase branch-B

  • step 1 :

    • git rebase -i HEAD~3
    • removed all commits from branch A and temporary keep them somewhere
  • step 2 : create a straight line of commits

    • use git log --oneline to check the commit status and id
    • use git rebase -i HEAD~3 to set the range of commit to rebase
    • next determine the desired action (reword or squash) only and don't edit the comment
      • reword -> edit comment
       reword 6bcf266 Optimize markup structure in inddpage
       pick 762317c Change the page structure
       pick del3564 Improve headline for improve
    
    • squash -> combine commit
      pick 6bcf266 Optimize markup structure in inddpage
      squash 762317c Change the page structure
      pick del3564 Improve headline for improve
    

    this will combine 6bcf266 and 762317c into new commit with new Id

  • step 3 : return back the commits of branch A with the new Id

home

Cherry Picking

  • allows you to select individual commits to be integrated
  • therfore use it for moving a commit to a different branch
  • when you commit to the wrong branch

for example: by using merge C2 and C4 from branch feature-X will all moved to branch master

by using cherry pick you can choice C2 or C4 only to move to branch master

   C1--------C3--------C5--------master
     \
      C2--------C4--------------feature-X

  • Usage Example:
    • WHen you committed on the wrong branch
    • C3 should have been on feature-X
   C1--------C3-----------master
     \
      C2------------------feature-X
  • first we shift to feature-X branch and apply cherry pick on the target commit
  git checkout feature/neweletter
  git cherry-pick 26bf1648
  • next clean up the commit from the master branch
  git checkout master
  git reset --hard HEAD~1 #this will remove the C3 from master branch

To add a new SSH key to your GitHub account, follow these steps:

Step 1: Generate a New SSH Key (if you don't have one already)

  1. Open your terminal (Git Bash, macOS Terminal, or Linux Terminal).

  2. Generate a new SSH key using the following command, replacing your_email@example.com with your GitHub email address:

    ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

    This will create a new SSH key. You’ll be prompted to choose a location for saving the key (press Enter to save it to the default location ~/.ssh/id_rsa).

  3. If you want to add a passphrase for extra security, you can do so. If not, press Enter twice to skip.

Step 2: Add the SSH Key to the SSH Agent

Now, you need to add the new SSH key to your SSH agent.

  1. Start the SSH agent in the background (for Linux/macOS):

    eval "$(ssh-agent -s)"
  2. Add the SSH private key to the SSH agent:

    ssh-add ~/.ssh/id_rsa

Step 3: Copy the SSH Public Key

  1. To view the SSH public key, run the following command:

    cat ~/.ssh/id_rsa.pub

    This will display your SSH public key.

  2. Copy the entire key (starting from ssh-rsa and ending with your email address).

Step 4: Add the SSH Key to Your GitHub Account

  1. Go to your GitHub account in your browser and sign in.
  2. Click on your profile picture in the top-right corner and select Settings.
  3. In the left sidebar, click SSH and GPG keys.
  4. Click the New SSH key button.
  5. In the Title field, give your SSH key a recognizable name (e.g., "My Laptop SSH Key").
  6. Paste the SSH public key you copied earlier into the Key field.
  7. Click Add SSH key.

Step 5: Test the SSH Connection

Now that your SSH key is added to GitHub, test the connection:

  1. In your terminal, run the following command:
    ssh -T git@github.com
    If everything is set up correctly, you should see a message like this:
    Hi your_username! You've successfully authenticated, but GitHub does not provide shell access.
    

Step 6: Use SSH for Your GitHub Repository

Finally, update your repository’s remote URL to use SSH instead of HTTPS:

  1. Go to your repository on GitHub and click the Code button.

  2. Copy the SSH URL, which will look like this:

    git@github.com:potatoscript/your_repository.git
    
  3. Update the remote URL in your local repository:

    git remote set-url origin git@github.com:potatoscript/your_repository.git

Set up SSH keys for two GitHub accounts on the same PC.

1. Generate SSH Keys for Both Accounts:

If you haven't already, generate two separate SSH keys for each GitHub account. You can do this using the following commands:

# For the first GitHub account
ssh-keygen -t rsa -b 4096 -C "your_email_1@example.com" -f ~/.ssh/id_rsa_account1

# For the second GitHub account
ssh-keygen -t rsa -b 4096 -C "your_email_2@example.com" -f ~/.ssh/id_rsa_account2
  • The -C flag is used to label the SSH key with the email associated with the account.
  • The -f flag allows you to specify a custom filename for the key. The default is id_rsa, but you want to name them differently (e.g., id_rsa_account1 and id_rsa_account2).

2. Add the SSH Keys to the SSH Agent:

Make sure your SSH agent is running, then add both keys to the agent:

# Start the SSH agent (if it's not already running)
eval "$(ssh-agent -s)"

# Add the first key
ssh-add ~/.ssh/id_rsa_account1

# Add the second key
ssh-add ~/.ssh/id_rsa_account2

3. Add SSH Keys to GitHub:

  • Log into each GitHub account and add the corresponding public key to each account.
    • For Account 1: Go to SettingsSSH and GPG keysNew SSH key, and paste the contents of ~/.ssh/id_rsa_account1.pub into the form.
    • For Account 2: Do the same for ~/.ssh/id_rsa_account2.pub on your second GitHub account.

4. Edit the SSH Config File:

Now, edit the SSH config file to specify which key to use for each GitHub account.

# Open the SSH config file for editing
nano ~/.ssh/config

Add the following configuration:

# For the first GitHub account
Host github.com-account1
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_account1

# For the second GitHub account
Host github.com-account2
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_account2
  • The Host entry is a unique name you’ll use to differentiate between the two accounts when you interact with GitHub.
  • The HostName is always github.com.
  • The IdentityFile points to the respective private key for each account.

5. Clone Repositories Using the Correct Host:

When cloning or interacting with a repository, use the Host alias you specified in the SSH config file:

  • For the first account:
git clone git@github.com-account1:username/repository.git
  • For the second account:
git clone git@github.com-account2:username/repository.git

When you use the alias (github.com-account1 or github.com-account2), SSH will automatically use the appropriate key for each GitHub account.

6. Switch Between Accounts (If Needed):

If you're already working with repositories and want to switch between accounts, you just need to ensure the correct Host alias is used in the Git URL.

  • For the first account, update the remote URL like this:
git remote set-url origin git@github.com-account1:username/repository.git
  • For the second account:
git remote set-url origin git@github.com-account2:username/repository.git

Check .gitconfig for Safe Directory Entries:

git config --global --edit

About

Distributed Version Control System

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published