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.
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,
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
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!
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
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
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
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.
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
Initialize a Repository.
Setup user details globally.
Setup project specific user details.
Check Configuration β List the configurations.
Problem 2
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.
Stage all files except one.
Problem 3
Commit with a message
Amend a commit
Commit without staging
Problem 4
Create a Branch
Create a new branch named feature/api to work on a feature independently without affecting the main branch.
Delete a branch.
Force delete a branch.
Rename a branch.
List all branches.
Problem 5
Switch to a branch
Switch to the main branch using git checkout.
Create and switch to a branch
Create a new branch named bugfix/001 and switch to it in a single command with git checkout -b.
Problem 6
Start with a repository containing a file named project.txt
Create two branches (feature-1 and feature-2) from the main branch.
Make changes to project.txt in both branches.
Attempt to merge feature-1 and feature-2 into the main branch.
Resolve any merge conflicts and complete the merge process.
Problem 7
View history in one-line format
Graphical commit history
Filter commits by Author
Show changes in a commit
Problem 8
Fetch updates from remote
Fetch and Merge
Fetch changes from the remote branch origin/main and merge them into your local main
List remote references
Problem 9
Create a stash
Apply a stash
Pop a stash
View stash
Problem 10
You need to undo the last commit but want to keep the changes staged for a new commit. What will you do ?
Problem 11
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
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 ?
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.
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.
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.
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,
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.
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 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.
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 [β¦]
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 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
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
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:
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.
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.
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.
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.
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.
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.