❌

Reading view

There are new articles available, click to refresh the page.

Effortless Git Repo Switching with a Simple Bash Function!

Why I Created This Function

At first, I used an alias

alias gitdir="cd ~/Git/" (This means gitdir switches to the ~/Git/ directory, but I wanted it to switch directly to a repository.)
So, I wrote a Bash function.

Write Code to .bashrc File

The .bashrc file runs when a new terminal window is opened.
So, we need to write the function inside this file.

Code

gitrepo() {
    # Exact Match
    repoList=$(ls $HOME/Git)
    if [ -n "$(echo "$repoList" | grep -w $1)" ]; then
	cd $HOME/Git/$1
    else
	# Relevant Match
	getRepoName=$(echo "$repoList" | grep -i -m 1 $1)
	
	if [ -n "$getRepoName" ]; then
	    cd "$HOME/Git/$getRepoName"
	else
	    echo "Repository Not Founded"
	    cd $HOME/Git
	fi
	
    fi   
}

Code Explanation

The $repoList variable stores the list of directories inside the Git folder.

Function Logic Has Two Parts:

  • Exact Match
  • Relevant Match

Exact Match

if [ -n "$(echo "$repoList" | grep -w $1)" ]; then
	cd $HOME/Git/$1

If condition: The $repoList variable parses input for grep.

  • grep -w matches only whole words.
  • $1 is the function’s argument in bash.
  • -n checks if a variable is not empty. Example syntax:
    [ a != "" ] is equivalent to [ -n a ]

Relevant Match

getRepoName=$(echo "$repoList" | grep -i -m 1 $1)
	if [ -n "$getRepoName" ]; then
	    cd "$HOME/Git/$getRepoName"

Relevant search: If no Exact Match is found, this logic is executed next.

getRepoName="$repoList" | grep -i -m 1 $1
  • -i ignores case sensitivity.
  • -m 1 returns only the first match.

Example of -m with grep:
ls | grep i3
It returns i3WM and i3status, but -m 1 ensures only i3WM is selected.

No Match

If no match is found, it simply changes the directory to the Git folder.

	else
	    echo "Repository Not Founded"
	    cd $HOME/Git

What I Learned

  • Basics of Bash functions
  • How to use .bashrc and reload changes.

20 Essential Git Command-Line Tricks Every Developer Should Know

Git is a powerful version control system that every developer should master. Whether you’re a beginner or an experienced developer, knowing a few handy Git command-line tricks can save you time and improve your workflow. Here are 20 essential Git tips and tricks to boost your efficiency.

1. Undo the Last Commit (Without Losing Changes)

git reset --soft HEAD~1

If you made a commit but want to undo it while keeping your changes, this command resets the last commit but retains the modified files in your staging area.

This is useful when you realize you need to make more changes before committing.

If you also want to remove the changes from the staging area but keep them in your working directory, use,

git reset HEAD~1

2. Discard Unstaged Changes

git checkout -- <file>

Use this to discard local changes in a file before staging. Be careful, as this cannot be undone! If you want to discard all unstaged changes in your working directory, use,

git reset --hard HEAD

3. Delete a Local Branch

git branch -d branch-name

Removes a local branch safely if it’s already merged. If it’s not merged and you still want to delete it, use -D

git branch -D branch-name

4. Delete a Remote Branch

git push origin --delete branch-name

Deletes a branch from the remote repository, useful for cleaning up old feature branches. If you mistakenly deleted the branch and want to restore it, you can use

git checkout -b branch-name origin/branch-name

if it still exists remotely.

5. Rename a Local Branch

git branch -m old-name new-name

Useful when you want to rename a branch locally without affecting the remote repository. To update the remote reference after renaming, push the renamed branch and delete the old one,

git push origin -u new-name
git push origin --delete old-name

6. See the Commit History in a Compact Format

git log --oneline --graph --decorate --all

A clean and structured way to view Git history, showing branches and commits in a visual format. If you want to see a detailed history with diffs, use

git log -p

7. Stash Your Changes Temporarily

git stash

If you need to switch branches but don’t want to commit yet, stash your changes and retrieve them later with

git stash pop

To see all stashed changes

git stash list

8. Find the Author of a Line in a File

git blame file-name

Shows who made changes to each line in a file. Helpful for debugging or reviewing historical changes. If you want to ignore whitespace changes

git blame -w file-name

9. View a File from a Previous Commit

git show commit-hash:path/to/file

Useful for checking an older version of a file without switching branches. If you want to restore the file from an old commit

git checkout commit-hash -- path/to/file

10. Reset a File to the Last Committed Version

git checkout HEAD -- file-name

Restores the file to the last committed state, removing any local changes. If you want to reset all files

git reset --hard HEAD

11. Clone a Specific Branch

git clone -b branch-name --single-branch repository-url

Instead of cloning the entire repository, this fetches only the specified branch, saving time and space. If you want all branches but don’t want to check them out initially:

git clone --mirror repository-url

12. Change the Last Commit Message

git commit --amend -m "New message"

Use this to correct a typo in your last commit message before pushing. Be cautiousβ€”if you’ve already pushed, use

git push --force-with-lease

13. See the List of Tracked Files

git ls-files

Displays all files being tracked by Git, which is useful for auditing your repository. To see ignored files

git ls-files --others --ignored --exclude-standard

14. Check the Difference Between Two Branches

git diff branch-1..branch-2

Compares changes between two branches, helping you understand what has been modified. To see only file names that changed

git diff --name-only branch-1..branch-2

15. Add a Remote Repository

git remote add origin repository-url

Links a remote repository to your local project, enabling push and pull operations. To verify remote repositories

git remote -v

16. Remove a Remote Repository

git remote remove origin

Unlinks your repository from a remote source, useful when switching remotes.

17. View the Last Commit Details

git show HEAD

Shows detailed information about the most recent commit, including the changes made. To see only the commit message

git log -1 --pretty=%B

18. Check What’s Staged for Commit

git diff --staged

Displays changes that are staged for commit, helping you review before finalizing a commit.

19. Fetch and Rebase from a Remote Branch

git pull --rebase origin main

Combines fetching and rebasing in one step, keeping your branch up-to-date cleanly. If conflicts arise, resolve them manually and continue with

git rebase --continue

20. View All Git Aliases

git config --global --list | grep alias

If you’ve set up aliases, this command helps you see them all. Aliases can make your Git workflow faster by shortening common commands. For example

git config --global alias.co checkout

allows you to use git co instead of git checkout.

Try these tricks in your daily development to level up your Git skills!

Learning Notes #61 – Undo a git pull

Today, i came across a blog on undo a git pull. In this blog, i have reiterated the blog in other words.

Mistakes happen. You run a git pull and suddenly find your repository in a mess. Maybe conflicts arose, or perhaps the changes merged from the remote branch aren’t what you expected.

Fortunately, Git’s reflog comes to the rescue, allowing you to undo a git pull and restore your repository to its previous state. Here’s how you can do it.

Understanding Reflog


Reflog is a powerful feature in Git that logs every update made to the tips of your branches and references. Even actions like resets or rebases leave traces in the reflog. This makes it an invaluable tool for troubleshooting and recovering from mistakes.

Whenever you perform a git pull, Git updates the branch pointer, and the reflog records this action. By examining the reflog, you can identify the exact state of your branch before the pull and revert to it if needed.

Step By Step Guide to UNDO a git pull

1. Check Your Current State Ensure you’re aware of the current state of your branch. If you have uncommitted changes, stash or commit them to avoid losing any work.


git stash
# or
git add . && git commit -m "Save changes before undoing pull"

2. Inspect the Reflog View the recent history of your branch using the reflog,


git reflog

This command will display a list of recent actions, showing commit hashes and descriptions. For example,


0a1b2c3 (HEAD -> main) HEAD@{0}: pull origin main: Fast-forward
4d5e6f7 HEAD@{1}: commit: Add new feature
8g9h0i1 HEAD@{2}: checkout: moving from feature-branch to main

3. Identify the Pre-Pull Commit Locate the commit hash of your branch’s state before the pull. In the above example, it’s 4d5e6f7, which corresponds to the commit made before the git pull.

4. Reset to the Previous Commit Use the git reset command to move your branch back to its earlier state,


git reset <commit-hash>

By default, it’s mixed so changes wont be removed but will be in staging.

The next time a pull operation goes awry, don’t panicβ€”let the reflog guide you back to safety!

git checkout HEAD filename

In GIT, usually when a commit occurs, HEAD points to the latest commit.

For an example, there is a commit made in a file. You further made some changes. Later at some point, you realize that change is not required anymore. In this case, you need to point the head to the old HEAD. Below command should be used.

git checkout HEAD <<filename>>

In a nutshell – above command is used to discard changes in the working directory

git reset HEAD filename

Imagine you made changes to file1.txt and file2.txt and added to staging area. Further you accidentally made some changes to file3.txt and added to staging area. Later you realize, changes made to file3.txt is unnecessary.

So, in order to remove file3.txt from staging area, use below command

git reset HEAD <<filename>>

basically this command is used to unstage changes from staging area.

Remember, this command only removes file from staging area. The changes you made to the file remains available.

git reset commit_SHA

Imagine if you have made 10 commits on a single file. If in case, if you need to discard all the changes from 6th commit, you would use this command so that all commits from 7th to 10th commit will be removed.

git reset 232bfg2

here 232bfg2 is first 7 characters of git commit SHA

git checkout HEAD filename

In GIT, usually when a commit occurs, HEAD points to the latest commit.

For an example, there is a commit made in a file. You further made some changes. Later at some point, you realize that change is not required anymore. In this case, you need to point the head to the old HEAD. Below command should be used.

git checkout HEAD <<filename>>

In a nutshell – above command is used to discard changes in the working directory

git reset HEAD filename

Imagine you made changes to file1.txt and file2.txt and added to staging area. Further you accidentally made some changes to file3.txt and added to staging area. Later you realize, changes made to file3.txt is unnecessary.

So, in order to remove file3.txt from staging area, use below command

git reset HEAD <<filename>>

basically this command is used to unstage changes from staging area.

Remember, this command only removes file from staging area. The changes you made to the file remains available.

git reset commit_SHA

Imagine if you have made 10 commits on a single file. If in case, if you need to discard all the changes from 6th commit, you would use this command so that all commits from 7th to 10th commit will be removed.

git reset 232bfg2

here 232bfg2 is first 7 characters of git commit SHA

Learning Notes #2 – Automate Email Notifications in GitHub Actions

Today, i was checking youtube videos on github actions. I came across a video on sending a mail via a Github Action https://www.youtube.com/watch?v=SkD7KQ3KzZs&t=108s. This blog is just an implementation of the video.

What am i going to do ?

I need to send a mail using my gmail id via Github

What prior information you need ?

  1. Gmail SMTP Server address – smtp.gmail.com
  2. Gmail SMTP port – 465
  3. Email username – your mail id.
  4. Email password – App Password from Google. https://support.google.com/accounts/answer/185833?hl=en.

YAML File


name: "Send Mail"

on:
  workflow_dispatch:

jobs:
  mail:
    runs-on: ubuntu-latest
    steps:
      - name: Print Name
        run: echo "Sending Mail"
    
      - name: Send Mail
        if: ${{ always() }}
        uses: dawidd6/action-send-mail@v3
        with:
          server_address: smtp.gmail.com
          server_port: 465

          username: ${{ secrets.EMAIL_USERNAME }}
          password: ${{ secrets.EMAIL_PASSWORD }}

          subject: ${{ github.job }} job of ${{ github.repository }} has  ${{ github.status }}
          body: "Test Message in Github"
          to:  syedjafer1997@gmail.com
          from: Syed Jafer K



My Github Run: https://github.com/syedjaferk/gh_actions_templates/actions/runs/12426929593

Learning Notes #01 – Github Actions

GitHub Actions is a CI/CD tool that automates workflows directly from your GitHub repository. I am writing this notes for my future self.

Github: https://github.com/syedjaferk/gh_action_docker_build_push_fastapi_app

0. Github Actions

Github Actions is a managed CI/CD pipeline offering. It provides free runners for running the code.

1. Workflow, Jobs, Steps

A workflow is a collection of jobs defined in a .yml file inside .github/workflows. Each workflow consists of jobs, and jobs have steps.


name: My First Workflow
on: push
jobs:
  example-job:
    runs-on: ubuntu-latest
    steps:
      - name: Print a message
        run: echo "Hello, GitHub Actions!"

2. Availability and Pricing

GitHub Actions is free for public repositories and has free usage limits for private repositories, depending on the plan. Paid plans increase these limits. For detailed pricing, visit the GitHub Actions pricing page.

3. First workflow with basic echo commands

Start with a workflow triggered by any push event. Here’s a simple example,


name: Echo Workflow
on: push
jobs:
  echo-job:
    runs-on: ubuntu-latest
    steps:
      - name: Say Hello
        run: echo "Hello from my first workflow!"

4. Multiline Shell Commands

You can use the | symbol to write multiline shell commands.


name: Push Event Workflow
on:
  push:
    branches:
      - main
jobs:
  push-job:
    runs-on: ubuntu-latest
    steps:
      - name: On Push
        run: echo "Code pushed to main branch!"

5. A new workflow with push events

Workflows can be triggered by specific events like push. This example triggers only on push to the main branch.


name: Push Event Workflow
on:
  push:
    branches:
      - main
jobs:
  push-job:
    runs-on: ubuntu-latest
    steps:
      - name: On Push
        run: echo "Code pushed to main branch!"

6. Using actions in workflow (Marketplace and Open Source)

GitHub Actions Marketplace offers reusable actions. For example, using the actions/checkout action.


steps:
  - name: Checkout Code
    uses: actions/checkout@v3

7. Checkout in code

Checking out your code is essential to access the repository content. Use actions/checkout


steps:
  - name: Checkout Code
    uses: actions/checkout@v3

8. Adding workflow job steps

Each job can have multiple steps.


jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Step 1 - Checkout Code
        uses: actions/checkout@v3
      - name: Step 2 - Run a Script
        run: echo "Script running in step 2."

9. Jobs in Parallel and Sequential

To run jobs in parallel, define them without dependencies. For sequential jobs, use needs.

Parallel Jobs:

jobs:
  job1:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Job 1"

  job2:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Job 2"

Sequential Jobs:


jobs:
  job1:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Job 1"

  job2:
    runs-on: ubuntu-latest
    needs: job1
    steps:
      - run: echo "Job 2 after Job 1"

10. Using Multiple Triggers

A workflow can be triggered by multiple events.


on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

11. Expressions and Context Objects

Expressions are used to access variables and contexts like github or env.


steps:
  - name: Use an Expression
    run: echo "Triggered by ${{ github.event_name }}"

Problem Statements : Git & Github Session – St. Joseph’s GDG Meeting

List of problem statements enough to get your hands dirty on git. These are the list of commands that you mostly use in your development.

Problem 1

  1. Initialize a Repository.
  2. Setup user details globally.
  3. Setup project specific user details.
  4. Check Configuration – List the configurations.

Problem 2

  1. Add Specific files. Create two files app.js and style.css. User git add to stage only style.css . This allows selective addition of files to the staging area before committing.
  2. Stage all files except one.

Problem 3

  1. Commit with a message
  2. Amend a commit
  3. Commit without staging

Problem 4

  1. Create a Branch
  2. Create a new branch named feature/api to work on a feature independently without affecting the main branch.
  3. Delete a branch.
  4. Force delete a branch.
  5. Rename a branch.
  6. List all branches.

Problem 5

  1. Switch to a branch
  2. Switch to the main branch using git checkout.
  3. Create and switch to a branch
  4. Create a new branch named bugfix/001 and switch to it in a single command with git checkout -b.

Problem 6

  1. Start with a repository containing a file named project.txt
  2. Create two branches (feature-1 and feature-2) from the main branch.
  3. Make changes to project.txt in both branches.
  4. Attempt to merge feature-1 and feature-2 into the main branch.
  5. Resolve any merge conflicts and complete the merge process.

Problem 7

  1. View history in one-line format
  2. Graphical commit history
  3. Filter commits by Author
  4. Show changes in a commit

Problem 8

  1. Fetch updates from remote
  2. Fetch and Merge
  3. Fetch changes from the remote branch origin/main and merge them into your local main
  4. List remote references

Problem 9

  1. Create a stash
  2. Apply a stash
  3. Pop a stash
  4. View stash

Problem 10

  1. You need to undo the last commit but want to keep the changes staged for a new commit. What will you do ?

Problem 11

  1. You realize you staged some files for commit but want to unstage them while keeping the changes in your working directory. Which git command will allow you to unstage the files without losing any change ?

Problem 12

  1. You decide to completely discard all local changes and reset the repository to the state of the last commit. What git command should you run to discard all changes and reset your working directory ?

Password Validator

import java.util.Scanner;

public class PasswordValidator {

	public static void main(String[] args) {
		// PASSWORD MUST CONTAIN MIN 8 CHARS, MAX 12 CHARS, ATLEAST 1 UPPERCASE, 1 LOWERCASE, 1 DIGIT, 1 SPL CHAR 
		Scanner scn = new Scanner(System.in);
		int maxLen = 12, minLen=8;
		System.out.println("Enter a password to validate");
		String pwd = scn.next();
		scn.close();
		int n = pwd.length();
		if (n<minLen || n>maxLen) {
			System.out.println("Password length must be between 8 to 12 characters");
			return;
		}
		char[] pw = pwd.toCharArray();
		int cntLower=0, cntUpper=0, cntDigit=0, cntSpl=0;
		for (int i=0; i<n; i++) {
			char ch = pw[i];
			if (ch>='A' && ch<='Z') cntUpper++;
			else if (ch>='a' && ch<='z') cntLower++;
			else if (ch>='1' && ch<='9') cntDigit++;
			else if (ch=='!' || ch=='Β£' || ch=='$' || ch=='%' || ch=='^' || ch=='&' || ch=='*' || ch=='-' || ch=='_' || ch=='+' || ch=='=' || ch==':' || ch==';' || ch=='@'|| ch=='#'|| ch=='~'|| ch=='>'|| ch=='<'|| ch=='?'|| ch=='.') cntSpl++; 
		}
		if (cntLower>0 && cntUpper>0 && cntDigit>0  && cntSpl>0) System.out.println("Password is valid...");
		else {
			System.out.println("Password is NOT VALID");
			System.out.println("PASSWORD MUST CONTAIN ATLEAST 1 UPPERCASE, 1 LOWERCASE, 1 DIGIT AND 1 SPL CHAR FROM ! Β£ $ % ^ & * - _ + = : ; @ ~ # ?");
		}
	}

}

Git

Git is a powerful version control system which used to manage the code across multiple users and track changes across different versions.

Installation:

Download and install GIT from the below path

https://git-scm.com/download/win

Once installed, Git can be used as a version control system through various commands.
You can configure Git for a specific folder on your computer, allowing you to manage all changes to existing files and the addition of new files within that folder

Basic commands:

1. git init:

This will initialize new repository in the current directory. This also creates .git directory and store all version control information.

2. git config:
git config --global user.name "Ranjith "
git config --global user.mail "ranjith201099@gmail.com"
3. git status

Shows the current status of working area like staged, untracked and unstaged.

4. git add

add changes from working directory to the staging area, preparing them to commit.

To add specific file: git add "filename.py"
To add all changes git add .
5. git commit
git commit -m "<message>"

Commits the staged changes with descriptive mesage

6. git log

Displays the list of commit history for the repository.
It will show commit id, author, dates and commit changes
Creating a branch

git branch <branch_name> - to create branch
git checkout <branch_name> - to switch to the new branch
git branch -b <branch_name> 

to create and switch to branch
git branch - to view all the branches (current branch will be highlighted with asterisk)

Merge a branch:

Once completed work on a branch and want to integrate it into another branch (like master), merging comes to place.

It means all the changes we have made in <branch_name> will be merged with master branch.
First, switch to the branch you want to merge into: git checkout master
Then, use git merge <branch_name> to merge your branch.
Deleting branch
Once the code changes in <branch_name> merged into <master> branch, we might need to delete branch.
use git branch -d <branch_name> to delete branch

Image description

Image description

Lucifer and the Git-Powered Calculator: The Complete Adventure

In losangels , a young coder named Lucifer set out on a mission to build his very own calculator. Along the way, he learned how to use Git, a powerful tool that would help him track his progress and manage his code. Here’s the complete story of how Lucifer built his calculator, step by step, with the power of Git.

Step 1: Setting Up the Project with git init

Lucifer started by creating a new directory for his project and initializing a Git repository. This was like setting up a magical vault to store all his coding adventures.


mkdir MagicCalculator
cd MagicCalculator
git init

This command created the .git directory inside the MagicCalculator folder, where Git would keep track of everything.

Step 2: Configuring His Identity with git config

Before getting too far, Lucifer needed to make sure Git knew who he was. He configured his username and email address, so every change he made would be recorded in his name.


git config --global user.name "Lucifer"
git config --global user.email "lucifer@codeville.com"

Step 3: Writing the Addition Function and Staging It with git add

Lucifer began his calculator project by writing a simple function to add two numbers. He created a new Python file named main.py and added the following code,


# main.py

def add(x, y):
    return x + y

# Simple test to ensure it's working
print(add(5, 3))  # Output should be 8

Happy with his progress, Lucifer used the git add command to stage his changes. This was like preparing the code to be saved in Git’s memory.


git add main.py

Step 4: Committing the First Version with git commit

Next, Lucifer made his first commit. This saved the current state of his project, along with a message describing what he had done.


git commit -m "Added addition function"

Now, Git had recorded the addition function as the first chapter in the history of Lucifer’s project.

Step 5: Adding More Functions and Committing Them

Lucifer continued to add more functions to his calculator. First, he added subtraction,


# main.py

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

# Simple tests
print(add(5, 3))       # Output: 8
print(subtract(5, 3))  # Output: 2

He then staged and committed the subtraction function,


git add main.py
git commit -m "Added subtraction function"

Lucifer added multiplication and division next,


# main.py

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y != 0:
        return x / y
    else:
        return "Cannot divide by zero!"

# Simple tests
print(add(5, 3))       # Output: 8
print(subtract(5, 3))  # Output: 2
print(multiply(5, 3))  # Output: 15
print(divide(5, 3))    # Output: 1.666...
print(divide(5, 0))    # Output: Cannot divide by zero!

Again, he staged and committed these changes,


git add main.py
git commit -m "Added multiplication and division functions"

Step 6: Branching Out with git branch and git checkout

Lucifer had an idea to add a feature that would let users choose which operation to perform. However, he didn’t want to risk breaking his existing code. So, he created a new branch to work on this feature.


git branch operation-choice
git checkout operation-choice

Now on the operation-choice branch, Lucifer wrote the code to let users select an operation,


# main.py

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y != 0:
        return x / y
    else:
        return "Cannot divide by zero!"

def calculator():
    print("Select operation:")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")

    choice = input("Enter choice (1/2/3/4): ")

    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))

    if choice == '1':
        print(f"{num1} + {num2} = {add(num1, num2)}")

    elif choice == '2':
        print(f"{num1} - {num2} = {subtract(num1, num2)}")

    elif choice == '3':
        print(f"{num1} * {num2} = {multiply(num1, num2)}")

    elif choice == '4':
        print(f"{num1} / {num2} = {divide(num1, num2)}")

    else:
        print("Invalid input")

# Run the calculator
calculator()

Step 7: Merging the Feature into the Main Branch

After testing his new feature and making sure it worked, Lucifer was ready to merge it back into the main branch. He switched back to the main branch and merged the changes


git checkout main
git merge operation-choice

With this, the feature was successfully added to his calculator project.

Conclusion: Lucifer’s Git-Powered Calculator

By the end of his adventure, Lucifer had built a fully functional calculator and learned how to use Git to manage his code. His calculator could add, subtract, multiply, and divide, and even let users choose which operation to perform.

Thanks to Git, Lucifer’s project was well-organized, and he had a complete history of all the changes he made. He knew that if he ever needed to revisit an old version or experiment with new features, Git would be there to help.

Lucifer’s calculator project was a success, and with his newfound Git skills, he felt ready to take on even bigger challenges in the future.

GIT - Basics

GIT is a powerful version control system which used to manage the code across multiple users and track changes across different versions.

Installation:

Download and install GIT from the below path
https://git-scm.com/download/win

  • Once installed, Git can be used as a version control system through various commands.
  • You can configure Git for a specific folder on your computer, allowing you to manage all changes to existing files and the addition of new files within that folder

Basic commands:

1. git init:

This will initialize new repository in the current directory. This also creates .git directory and store all version control information.

2. git config:
git config --global user.name "Suresh"
git config --global user.mail "Suresh.Sundararaju@gmail.com"

3. git status
Shows the current status of working area like staged, untracked and unstaged.

4. git add
add changes from working directory to the staging area, preparing them to commit.

  • To add specific file: git add "filename.py"
  • To add all changes git add .

5. git commit

  • git commit -m "<message>"
  • Commits the staged changes with descriptive mesage

6. git log

  • Displays the list of commit history for the repository.
  • It will show commit id, author, dates and commit changes

Creating a branch

  • git branch <branch_name> - to create branch
  • git checkout <branch_name> - to switch to the new branch
  • git branch -b <branch_name> - to create and switch to branch
  • git branch - to view all the branches (current branch will be highlighted with asterisk)

Merge a branch:
Once completed work on a branch and want to integrate it into another branch (like master), merging comes to place.

  • It means all the changes we have made in <branch_name> will be merged with master branch.
  • First, switch to the branch you want to merge into: git checkout master
  • Then, use git merge <branch_name> to merge your branch.

Deleting branch
Once the code changes in <branch_name> merged into <master> branch, we might need to delete branch.

  • use git branch -d <branch_name> to delete branch

import Project from Github to Eclipse

Click Next and Next Accept the license and click finish to complete installation. click file menu and chose import option select Git option and choose Project from GitHub and select clone URL Open your github project and copy the .git url paste below URL into that URL click next and next then click finish to […]

Types of Version Control System

version control system tracks changes to a file or set of files over time. There are three types of version control system: Local Version Control Systems: Centralized Version Control Systems: Distributed Version Control Systems: Popular version control systems and tools Here’s a brief overview of some commonly used version control tools and their pros and […]

Git Commands

  • git clone
  • git add
  • git commit
  • git push
  • git pull
  • git branch
  • git checkout
  • git status

git clone remote

to create new repository in github cloud , then create a local repo and clone 2 repositories using git clone remote (repo link).

git add filename
git add .

to add a single file using git add and add all the files which present in the current repo the use git add . | . represent add all the files.

git commit -m "message"

commit the added file using git commit and put some mesagges about the file using -m ” ” .

some ideas of commit messages are available in below mentioned link.

Reference : conventional commit.org | https://www.conventionalcommits.org/en/v1.0.0/

git rm --cached filename
if incase want to remove the added file use git remove
git rm --cached -f filename
-f --> forcefully remove the file.
git push

push the commited file from the local to cloud repo using git push. it will push the file to remote repository.

git pull 

when u need to change or edit or modify the remote file first you will pull the file to local repository from remote using git pull.

git branch 
Branch means where will you store the files in git remote.git branch is to specify the branch name it will push the file to current remote branch.

git checkout -b "branchname"
to create a new branch.

git checkout branchname
check the created branch or new branch

git branch -M branchname
to modify or change the branch name

git branch -a
to listout all branches.
git status
check all the status of previously used command like know the added file is staged or unstaged

Reference : https://www.markdownguide.org/cheat-sheet/

markdown cheathseet for readme file

Reference : conventional commit.org | https://www.conventionalcommits.org/en/v1.0.0/

for commit messages.

Git Commands

  • git clone
  • git add
  • git commit
  • git push
  • git pull
  • git branch
  • git checkout
  • git status

git clone remote

to create new repository in github cloud , then create a local repo and clone 2 repositories using git clone remote (repo link).

git add filename
git add .

to add a single file using git add and add all the files which present in the current repo the use git add . | . represent add all the files.

git commit -m "message"

commit the added file using git commit and put some mesagges about the file using -m ” ” .

some ideas of commit messages are available in below mentioned link.

Reference : conventional commit.org | https://www.conventionalcommits.org/en/v1.0.0/

git rm --cached filename
if incase want to remove the added file use git remove
git rm --cached -f filename
-f --> forcefully remove the file.
git push

push the commited file from the local to cloud repo using git push. it will push the file to remote repository.

git pull 

when u need to change or edit or modify the remote file first you will pull the file to local repository from remote using git pull.

git branch 
Branch means where will you store the files in git remote.git branch is to specify the branch name it will push the file to current remote branch.

git checkout -b "branchname"
to create a new branch.

git checkout branchname
check the created branch or new branch

git branch -M branchname
to modify or change the branch name

git branch -a
to listout all branches.
git status
check all the status of previously used command like know the added file is staged or unstaged

Reference : https://www.markdownguide.org/cheat-sheet/

markdown cheathseet for readme file

Reference : conventional commit.org | https://www.conventionalcommits.org/en/v1.0.0/

for commit messages.

GitHub, Git & Jenkins

Github:

It allows collaboration with any developer all over the world. Open Source solutions enable potential developer to contribute and share the knowledge to benefit the Global Community. At a high level, GitHub is a website and cloud-based service that helps developers store and manage their code, as well as track and control changes to their code. To understand exactly what GitHub is, you need to know two connected principles:

  • Version control
  • Git

What Is Version Control?

Version control helps developers track and manage changes to a software project’s code. As a software project grows, version control becomes essential. Take WordPress…

At this point, WordPress is a pretty big project. If a core developer wanted to work on one specific part of the WordPress codebase, it wouldn’t be safe or efficient to have them directly edit the β€œofficial” source code.

Instead, version control lets developers safely work throughΒ branchingΒ andΒ merging.

WithΒ branching, a developer duplicates part of the source code (called theΒ repository). The developer can then safely make changes to that part of the code without affecting the rest of the project.

Then, once the developer gets his or her part of the code working properly, he or she canΒ mergeΒ that code back into the main source code to make it official.

What Is Git?

Git is aΒ specific open-source version control systemΒ created by Linus Torvalds in 2005.It is used for coordinating work among several people on a project and track progress over time. It is used for source code management for software development.

GitHub is a Git repository hosting service which provides a web-based graphical interface that helps every team member to work together on the project from anywhere and makes it easy to collaborate.

Jenkins

Jenkins isΒ a Java-based open-source automation platform with plugins designed for continuous integration.

It helps automate the parts of software development related to building, testing, and deploying, facilitating continuous integration, and continuous delivery, making it easier for developers and DevOps engineers to integrate changes to the project and for consumers to get a new build. It is a server-based system that runs in servlet containers such as Apache Tomcat.

Git vs Jenkins: What are the differences?

Git and Jenkins are both popular tools, Git is a distributed version control system and Jenkins is a continuous integration and automation tool. Let’s explore the key differences between the two:

  1. Code Management vs. Automated Builds: Git is primarily used for code management and version control. It allows developers to track changes, collaborate on code, and handle code branching and merging efficiently. On the other hand, Jenkins focuses on automated builds, testing, and deployment. It helps in integrating code changes from multiple team members and automates the build process, including compiling, testing, and packaging the software.
  2. Local vs. Remote: Git operates locally on the developer’s machine, allowing them to work offline and commit changes to their local repository. Developers can then push their changes to a remote repository, facilitating collaboration with other team members. In contrast, Jenkins is a remote tool that runs on a dedicated server or cloud platform. It continuously monitors the code repository and triggers automated builds or tests based on predefined conditions or schedules.
  3. Version Control vs. Continuous Integration: Git’s primary focus is on version control, tracking changes to files and directories over time. It provides features like branching, merging, and resolving conflicts to manage code versions effectively. Jenkins, on the other hand, emphasizes continuous integration (CI), which involves frequently integrating code changes from multiple developers into a shared repository. Jenkins automatically builds and tests the integrated code, highlighting any conflicts or issues that arise during the process.
  4. User Interface: Git primarily relies on a command-line interface (CLI) for executing various operations. However, there are also graphical user interface (GUI) clients available for more user-friendly interactions. Jenkins, on the other hand, provides a web-based graphical user interface that allows users to configure and manage Jenkins jobs, view build reports, and monitor the status of automated builds and tests.
  5. Plugin Ecosystem: Git has an extensive ecosystem of third-party plugins that extend its functionality and integrations with other development tools. These plugins cover various areas, including code review, issue tracking, and build automation. Jenkins, being an automation tool, has a rich plugin ecosystem as well. These plugins enable users to integrate Jenkins with different build tools, testing frameworks, version control systems, and deployment platforms, enhancing its capabilities and flexibility.
  6. Ease of Use: Git can have a steep learning curve for beginners, particularly when it comes to understanding concepts like branching, merging, and resolving conflicts. However, once users become familiar with its core functionality, it provides a powerful and flexible version control system. Jenkins, on the other hand, aims to simplify the CI process and provide an intuitive user interface for managing builds and automation. While some initial setup and configuration may be required, Jenkins offers ease of use in terms of managing continuous integration workflows.

In summary, Git focuses on code management and version control, while Jenkins specializes in continuous integration and automation. Git operates locally, while Jenkins runs remotely on dedicated servers. Git’s primary interface is command-line-based, with additional GUI clients available, whereas Jenkins offers a web-based graphical user interface. Both Git and Jenkins have plugin ecosystems that extend their functionality, but Jenkins prioritizes automation-related integrations. Finally, while Git has a steeper learning curve, Jenkins aims to provide ease of use in managing continuous integration workflows.

Source: https://stackshare.io/stackups/git-vs-jenkins#:~:text=Git%20operates%20locally%2C%20while%20Jenkins,web%2Dbased%20graphical%20user%20interface.

Github Configuration Commands

sudo apt update git
sudo apt install git
git --version
git config --global user.name "Muthukumark98"
git config --global user.email "muthukumar1998mk98@gmail.com"
git config --list
pwd
mkdir workspace
cd workspace/
git clone https://github.com/Muthukumark98/hello_test.git
ls
cd hello_test/
touch hello.py
ls
cat README.md 
ls
vim hello.py
cat hello.py
git status
git add hello.py
git status
git commit -m "first python code"
git status
git push origin main
git remote set-url origin https://<token>/<username>/<repo>
git push origin main
❌