Git

Version Control (also called Source Control) is a system that tracks changes to files over time so that you can recall specific versions later.

GIT full form is “Global Information Tracker,” a powerful version control system widely used for software development and other collaborative projects. GIT allows multiple developers to work on a project simultaneously while ensuring that their changes do not interfere with one another.

  • consider git as tree 
  • trunk/master is one n has branches.

🚀 Git Branching Workflow (Git Flow)

This model uses a set of dedicated branches for managing features, releases, and hotfixes, making it ideal for managing large-scale software projects.


🔵 0. Main / Master / Trunk Branch

  • Purpose: Holds production-ready code.

  • Behavior: Continuously integrated and contains official release history.

  • Rule: Only stable code gets merged into this branch.


🟡 1. develop Branch

  • Purpose: Acts as the integration branch for features.

  • Usage: All features and changes are first merged into develop before going to main.

  • Command:

    git branch develop git push -u origin develop

🟢 2. Feature Branches

  • Purpose: For developing new features or enhancements.

  • Base Branch: develop

  • Merge Target: develop

  • Naming: feature/<feature-name>

  • Commands:

    git checkout develop git checkout -b feature/feature-name

🔴 3. Release Branches

  • Purpose: Prepares the codebase for production release.

  • Base Branch: develop

  • Merge Target: main and develop

  • Naming: release/<version>

  • Commands:

    git checkout develop git checkout -b release/0.1.0
  • After Testing:

    git checkout main git merge release/0.1.0 git tag -a v0.1.0 -m "Release 0.1.0" git checkout develop git merge release/0.1.0 git branch -d release/0.1.0

🟠 4. Hotfix Branches

  • Purpose: Quickly fix bugs in production.

  • Base Branch: main

  • Merge Target: main and develop

  • Naming: hotfix/<issue-name>

  • Commands:

    git checkout main git checkout -b hotfix/urgent-fix
  • After Fixing:

    git checkout main git merge hotfix/urgent-fix git tag -a v0.1.1 -m "Hotfix 0.1.1" git checkout develop git merge hotfix/urgent-fix git branch -d hotfix/urgent-fix

================================================================


🔐 What is a Git SSH Key?

An SSH key is a cryptographic credential used to securely connect to remote repositories (like GitHub, GitLab, Bitbucket) without entering your username and password every time.

It uses:

  • Public Key: Shared with the remote (like Bitbucket).

  • Private Key: Stored securely on your machine. Never share it.

This setup allows Git to authenticate securely when pushing/pulling code.

How to Generate and Use a Git SSH Key

  • ssh-keygen -t ecdsa -C "your_email@example.com"
  • add public key to bucket
  • eval "$(ssh-agent -s)"
  • ssh-add /path/to/your/private_key


================================================================


SETUP 

Configuring user information used across all local repositories 

>git config --global user.name “[firstname lastname]”  -- set a name that is identifiable for credit when review version history 

>git config --global user.email “[valid-email]”  -- set an email address that will be associated with each history marker 

>git config --global color.ui auto -- set automatic command line coloring for Git for easy reviewing

=================================================

STAGE & SNAPSHOT 

Working with snapshots and the Git staging area 

>git status show modified files in working directory, staged for your next commit 

>git add [file] -- add a file as it looks now to your next commit (stage) 

>git reset [file] -- unstage a file while retaining the changes in working directory 

>git diff diff of what is changed but not staged 

>git diff --staged diff of what is staged but not yet committed 

>git commit -m “[descriptive message]” -- commit your staged content as a new commit snapshot


BRANCH & MERGE 

Isolating work in branches, changing context, and integrating changes 

>git branch list your branches. a * will appear next to the currently active branch 

>git branch [branch-name] create a new branch at the current commit 

>git checkout [branch] switch to another branch and check it out into your working directory 

$ git checkout -b iss53
Switched to a new branch "iss53"

>git merge [branch] merge the specified branch’s history into the current one 

>git log show all commits in the current branch’s history



INSPECT & COMPARE 

Examining logs, diffs and object information 

>git log show the commit history for the currently active branch 

>git log branchB..branchA show the commits on branchA that are not on branchB 

>git log --follow [file] show the commits that changed file, even across renames 

>git diff branchB...branchA show the diff of what is in branchA that is not in branchB 

>git show [SHA] show any object in Git in human-readable format


SHARE & UPDATE 

Retrieving updates from another repository and updating local repos 

>git remote add [alias] [url] add a git URL as an alias 

>git fetch [alias] fetch down all the branches from that Git remote 

>git merge [alias]/[branch] merge a remote branch into your current branch to bring it up to date 

>git push [alias] [branch] Transmit local branch commits to the remote repository branch 

>git pull fetch and merge any commits from the tracking remote branch


REWRITE HISTORY 

Rewriting branches, updating commits and clearing history 

>git rebase [branch] apply any commits of current branch ahead of specified one 

>git reset --hard [commit] clear staging area, rewrite working tree from specified commit

TEMPORARY COMMITS 

Temporarily store modified, tracked files in order to change branches 

>git stash Save modified and staged changes 

>git stash list list stack-order of stashed file changes 

>git stash pop write working from top of stash stack 

>git stash drop discard the changes from top of stash stack


>git checkout chgbrnch -- change branch

>git checkout -b newbrnch -- create new branch n move but not yet push

=======================================================

🧱 1. Initializing a Repository

🔹 Create a New Git Repository


git init <project-directory>
  • This creates a .git folder inside the directory.

  • It initializes a new main branch (or master, depending on config).

  • It’s a one-time setup for a new project.


🔄 2. Cloning a Repository

🔹 Clone an Existing Remote Repo


git clone <repository-url>
  • Clones the entire codebase, including its .git history, into a new local directory.

  • Typically used to start working on existing GitHub/Bitbucket projects.


⚙️ 3. Git Configuration

Git lets you configure settings at 3 levels:

view all config

git config --list --show-origin 

==================================================================

🌿 git branch – Branch Management in Git

==================================================================


GIT ADD



==================================================================

🔖 What is a Tag in Git?

A Git tag is a marker that points to a specific commit in your Git history — typically used to mark version releases like v1.0, v2.1, etc.


==================================================================

Log , status , clean



=========================================================

git revert and git reset


🔁 Git Revert"Undo, but keep the history"

➤ What it does:

  • Creates a new commit that reverses the changes made by an earlier commit.

  • Does not delete the original commit.

  • Used when you want to undo a change safely, especially in shared/public branches.

➤ Analogy:

Think of it like writing something in a notebook, then adding a new note that says:

“Ignore the previous page, it was wrong.”

You're not tearing out the old page—you’re adding a new page to cancel it out.

➤ Example:


git revert HEAD

This creates a new commit that undoes the last commit.


🔄 Git Reset"Rewind history"

➤ What it does:

  • Moves the pointer of your branch (HEAD) backward in time to a previous commit.

  • You can choose whether to keep your file changes or discard them depending on the flag used:

    • --soft: Keep changes staged

    • --mixed: Keep changes in working directory (unstaged)

    • --hard: Discard all changes (⚠ deletes!)

➤ Analogy:

It's like going back in time and rewriting the past—as if the later commits never happened.

➤ Example:

git reset --hard HEAD~1

This removes the most recent commit and all its changes.


==================================================================

🔀 Git Merge vs Git Rebase

🟦 Git Merge

What it does:
Combines changes from one branch into another by creating a merge commit that ties together the histories of both branches.

➤ Example:

git checkout master git merge feature

This creates a commit like:


A---B---C---F (master) \ / D---E (feature)

  • Creates a merge commit F

  • Keeps the original branch structure

  • Useful in team environments to preserve history


🟨 Git Rebase

What it does:
Moves or "replays" your branch commits on top of another branch, rewriting history to make it linear.

➤ Example:

git checkout feature git rebase master

This turns:


A---B---C (master) \ D---E (feature)

Into:


A---B---C---D'---E' (feature rebased on master)

  • No merge commits

  • Cleaner, linear history

  • Changes commit hashes because it rewrites commits



==================================================================

🧾 git diff — Compare Changes in Git

The git diff command is used to show the differences between:

  • Your working directory and the staging area

  • The staging area and the last commit




=============================================================

🍒 git cherry-pick — Apply Specific Commits from Another Branch

git cherry-pick is used to selectively apply a specific commit from one branch to another. It reapplies the changes introduced by the chosen commit(s) as a new commit on your current branch.




=============================================================

🌐 git remote — Manage Remote Repositories in Git

The git remote command lets you connect your local repository to remote repositories (like GitHub, GitLab, Bitbucket, etc.). This is how you push your local changes to the cloud and pull updates from collaborators.


🛠️ Example Workflow

✅ 1. Add a Remote


git remote add origin https://github.com/your-username/your-repo.git

  • origin is the name of the remote (a convention)

  • The URL is the remote repository's address

🔍 2. View Remotes


git remote -v

origin https://github.com/your-username/your-repo.git (fetch) origin https://github.com/your-username/your-repo.git (push)

🚀 3. Push to Remote


git push origin main

Pushes your local main branch to the remote named origin.


📥 4. Pull from Remote


git pull origin main

Gets the latest changes from the remote main branch.

========================================================

Git fetch

🔄 git fetch — Download Changes from Remote Without Merging

The git fetch command downloads commits, files, and refs from a remote repository into your local repo, but does not automatically merge those changes into your working branch.

🧠 Key Idea:

Use git fetch when you want to see what's new in the remote before integrating it into your local branch.


 

📥 What git fetch Does:

  • Gets the latest commit history and branch updates from the remote.

  • Updates your local references (e.g., origin/main) to match the remote.

  • Does NOT modify your working directory or staging area.


========================================================

Git push

🚀 git push — Upload Your Local Changes to a Remote Repository

The git push command is used to upload local commits to a remote repository. It updates the remote branch with changes made in your local branch.

========================================================

Git checkout

🧭 git checkout — Switch Branches or Restore Files

The git checkout command is a multi-purpose tool used to:

  1. Switch between branches

  2. Restore files or commits

  3. Create new branches (with -b)

















Git Cheat Sheet

1. Git configuration

  • Git config
    Get and set configuration variables that control all facets of how Git looks and operates.
    Set the name:
    $ git config --global user.name "User name"
    Set the email:
    $ git config --global user.email "himanshudubey481@gmail.com"
    Set the default editor:
    $ git config --global core.editor Vim
    Check the setting:
    $ git config -list
  • Git alias
    Set up an alias for each command:
    $ git config --global alias.co checkout
    $ git config --global alias.br branch
    $ git config --global alias.ci commit
    $ git config --global alias.st status

2. Starting a project

  • Git init
    Create a local repository:
    $ git init
  • Git clone
    Make a local copy of the server repository.
    $ git clone

3. Local changes

  • Git add
    Add a file to staging (Index) area:
    $ git add Filename
    Add all files of a repo to staging (Index) area:
    $ git add*
  • Git commit
    Record or snapshots the file permanently in the version history with a message.
    $ git commit -m " Commit Message"

4. Track changes

  • Git diff
    Track the changes that have not been staged: $ git diff
    Track the changes that have staged but not committed:
    $ git diff --staged
    Track the changes after committing a file:
    $ git diff HEAD
    Track the changes between two commits:
    $ git diff Git Diff Branches:
    $ git diff < branch 2>
  • Git status
    Display the state of the working directory and the staging area.
    $ git status
  • Git show Shows objects:
    $ git show

5. Commit History

  • Git log
    Display the most recent commits and the status of the head:
    $ git log
    Display the output as one commit per line:
    $ git log -oneline
    Displays the files that have been modified:
    $ git log -stat
    Display the modified files with location:
    $ git log -p
  • Git blame
    Display the modification on each line of a file:
    $ git blame <file name>

6. Ignoring files

  • .gitignore
    Specify intentionally untracked files that Git should ignore. Create .gitignore:
    $ touch .gitignore List the ignored files:
    $ git ls-files -i --exclude-standard

7. Branching

  • Git branch Create branch:
    $ git branch List Branch:
    $ git branch --list Delete a Branch:
    $ git branch -d Delete a remote Branch:
    $ git push origin -delete Rename Branch:
    $ git branch -m
  • Git checkout
    Switch between branches in a repository.
    Switch to a particular branch:
    $ git checkout
    Create a new branch and switch to it:
    $ git checkout -b Checkout a Remote branch:
    $ git checkout
  • Git stash
    Switch branches without committing the current branch. Stash current work:
    $ git stash
    Saving stashes with a message:
    $ git stash save ""
    Check the stored stashes:
    $ git stash list
    Re-apply the changes that you just stashed:
    $ git stash apply
    Track the stashes and their changes:
    $ git stash show
    Re-apply the previous commits:
    $ git stash pop
    Delete a most recent stash from the queue:
    $ git stash drop
    Delete all the available stashes at once:
    $ git stash clear
    Stash work on a separate branch:
    $ git stash branch
  • Git cherry pic
    Apply the changes introduced by some existing commit:
    $ git cherry-pick

8. Merging

  • Git merge
    Merge the branches:
    $ git merge
    Merge the specified commit to currently active branch:
    $ git merge
  • Git rebase
    Apply a sequence of commits from distinct branches into a final commit.
    $ git rebase
    Continue the rebasing process:
    $ git rebase -continue Abort the rebasing process:
    $ git rebase --skip
  • Git interactive rebase
    Allow various operations like edit, rewrite, reorder, and more on existing commits.
    $ git rebase -i

9. Remote

  • Git remote
    Check the configuration of the remote server:
    $ git remote -v
    Add a remote for the repository:
    $ git remote add Fetch the data from the remote server:
    $ git fetch
    Remove a remote connection from the repository:
    $ git remote rm
    Rename remote server:
    $ git remote rename
    Show additional information about a particular remote:
    $ git remote show
    Change remote:
    $ git remote set-url
  • Git origin master
    Push data to the remote server:
    $ git push origin master Pull data from remote server:
    $ git pull origin master

10. Pushing Updates

  • Git push
    Transfer the commits from your local repository to a remote server. Push data to the remote server:
    $ git push origin master Force push data:
    $ git push -f
    Delete a remote branch by push command:
    $ git push origin -delete edited

11. Pulling updates

  • Git pull
    Pull the data from the server:
    $ git pull origin master
    Pull a remote branch:
    $ git pull
  • Git fetch
    Download branches and tags from one or more repositories. Fetch the remote repository:
    $ git fetch< repository Url> Fetch a specific branch:
    $ git fetch
    Fetch all the branches simultaneously:
    $ git fetch -all
    Synchronize the local repository:
    $ git fetch origin

12. Undo changes

  • Git revert
    Undo the changes:
    $ git revert
    Revert a particular commit:
    $ git revert
  • Git reset
    Reset the changes:
    $ git reset -hard
    $ git reset -soft:
    $ git reset --mixed

13. Removing files

  • Git rm
    Remove the files from the working tree and from the index:
    $ git rm <file Name>
    Remove files from the Git But keep the files in your local repository:
    $ git rm --cached





















Git Init

The git init command is the first command that you will run on Git. The git init command is used to create a new blank repository. It is used to make an existing project as a Git project. Several Git commands run inside the repository, but init command can be run outside of the repository.

The git init command creates a .git subdirectory in the current working directory. This newly created subdirectory contains all of the necessary metadata. These metadata can be categorized into objects, refs, and temp files. It also initializes a HEAD pointer for the master branch of the repository.

Creating the first repository

Git version control system allows you to share projects among developers. For learning Git, it is essential to understand that how can we create a project on Git. A repository is a directory that contains all the project-related data. There can also be more than one project on a single repository.

We can create a repository for blank and existing projects. Let's understand how to create a repository.

Create a Repository for a Blank (New) Project:

To create a blank repository, open command line on your desired directory and run the init command as follows:

  1. $ git init  

The above command will create an empty .git repository. Suppose we want to make a git repository on our desktop. To do so, open Git Bash on the desktop and run the above command. Consider the below output:

Git Init

The above command will initialize a .git repository on the desktop. Now we can create and add files on this repository for version control.

To create a file, run the cat or touch command as follows:

  1. $ touch <file Name>  

To add files to the repository, run the git add command as follows:

  1. $ git add <file name>  

Learn more about git add command visit Git Add.

Create a Repository for an existing project

If you want to share your project on a version control system and control it with Git, then, browse your project's directory and start the git command line (Git Bash for Windows) here. To initialize a new repository, run the below command:

Syntax:

  1. $ git init  

Output:

Git Init

The above command will create a new subdirectory named .git that holds all necessary repository files. The .git subdirectory can be understood as a Git repository skeleton. Consider the below image:

Git Init

An empty repository .git is added to my existing project. If we want to start version-controlling for existing files, we have to track these files with git add command, followed by a commit.

We can list all the untracked files by git status command.

  1. $ git status    

Consider the below output:

Git Init

In the above output, the list of all untracked files is displayed by the git status command. To learn more about status command, visit Git Status.

We can track all the untracked files by Git Add command.

Create a Repository and Directory Together

The git init command allows us to create a new blank repository and a directory together. The empty repository .git is created under the directory. Suppose I want to create a blank repository with a project name, then we can do so by the git init command. Consider the below command:

  1. $ git init NewDirectory  

The above command will create an empty .git repository under a directory named NewDirectory. Consider the below output:

Git Init

In the above output, the directory and the repository both are created.

Hence we can create a repository using git init command. Two other commands are handy to start with git. They are Git Add, and Git commit.

Git Tags

Tags make a point as a specific point in Git history. Tags are used to mark a commit stage as relevant. We can tag a commit for future reference. Primarily, it is used to mark a project's initial point like v1.1.

Tags are much like branches, and they do not change once initiated. We can have any number of tags on a branch or different branches. The below figure demonstrates the tags on various branches.

Git Tags

In the above image, there are many versions of a branch. All these versions are tags in the repository.

There are two types of tags.

  • Annotated tag
  • Light-weighted tag

Both of these tags are similar, but they are different in case of the amount of Metadata stores.

When to create a Tag:

  • When you want to create a release point for a stable version of your code.
  • When you want to create a historical point that you can refer to reuse in the future.

Git Create tag

To create a tag first, checkout to the branch where you want to create a tag. To check out the branch, run the below command:

  1. $ git checkout <Branch name>  

Now, you are on your desired branch, say, master. Consider the below output:

Git Tags

You can create a tag by using the git tag command. Create a tag with some name say v1.0, v1.1, or any other name whatever you want. To create a tag, run the command as follows:

Syntax:

  1. $ git tag <tag name>  

The above command will mark the current status of the project. Consider the below example:

  1. $ git tag projectv1.0  
Git Tags

The above command will create a mark point on the master branch as projectv1.0.

Git List Tag

We can list the available tags in our repository. There are three options that are available to list the tags in the repository. They are as follows:

  • git tag
  • git show
  • git tag -l ".*"

The "git tag":

It is the most generally used option to list all the available tags from the repository. It is used as:

  1. $ git tag  

Output:

Git Tags

As we can see from the above output, the git tag command is listing the available tags from the repository.

The git tag show <tagname>:

It's a specific command used to display the details of a particular tag. It is used as:

Syntax:

  1. $ git tag show <tagname>  

The above command will display the tag description, consider the below command:

  1. $ git tag show projectv1.0  

Output:

Git Tags

In the above output, the git show tag is displaying the description of tag projectv1.0, such as author name and date.

The git tag -l ".*":

It is also a specific command-line tool. It displays the available tags using wild card pattern. Suppose we have ten tags as v1.0, v1.1, v1.2 up to v1.10. Then, we can list all v pattern using tag pattern v. it is used as:

Syntax:

  1. $ git tag -l "<pattern>.*"  

The above command will display all the tags that contain wild card characters. Consider the below command:

  1. $ git tag -l "pro*"  

Output:

Git Tags

The above command is displaying a list of the tags that started with a word pro.

Git Ignore

In Git, the term "ignore" is used to specify intentionally untracked files that Git should ignore. It doesn't affect the Files that already tracked by Git.

Sometimes you don't want to send the files to Git service like GitHub. We can specify files in Git to ignore.

The file system of Git is classified into three categories:

Tracked:

Tracked files are such files that are previously staged or committed.

Untracked:

Untracked files are such files that are not previously staged or committed.

Ignored:

Ignored files are such files that are explicitly ignored by git. We have to tell git to ignore such files.

Generally, the Ignored files are artifacts and machine-generated files. These files can be derived from your repository source or should otherwise not be committed. Some commonly ignored files are as follows:

  • dependency caches
  • compiled code
  • build output directories, like /bin, /out, or /target
  • runtime file generated, like .log, .lock, or .tmp
  • Hidden system files, like Thumbs.db or.DS_Store
  • Personal IDE config files, such as .idea/workspace.xml

Git Ignore Files

Git ignore files is a file that can be any file or a folder that contains all the files that we want to ignore. The developers ignore files that are not necessary to execute the project. Git itself creates many system-generated ignored files. Usually, these files are hidden files. There are several ways to specify the ignore files. The ignored files can be tracked on a .gitignore file that is placed on the root folder of the repository. No explicit command is used to ignore the file.

There is no explicit git ignore command; instead, the .gitignore file must be edited and committed by hand when you have new files that you wish to ignore. The .gitignore files hold patterns that are matched against file names in your repository to determine whether or not they should be ignored.

How to Ignore Files Manually

There is no command in Git to ignore files; alternatively, there are several ways to specify the ignore files in git. One of the most common ways is the .gitignore file. Let's understand it with an example.

The .gitignore file:

Rules for ignoring file is defined in the .gitignore file. The .gitignore file is a file that contains all the formats and files of the ignored file. We can create multiple ignore files in a different directory. Let's understand how it works with an example:

Step1: Create a file named .gitignore if you do not have it already in your directory. To create a file, use the command touch or cat. It will use as follows:

  1. $ touch .gitignore  

Or

  1. $ cat .gitignore  

The above command will create a .gitignore file on your directory. Remember, you are working on your desired directory. Consider the below command:

Git Ignore

The above command will create a file named .gitignored. We can track it on the repository. Consider the below image:

Git Ignore

As you can see from the above image, a .gitignore file has been created for my repository.

Step2: Now, add the files and directories to the .gitignore file that you want to ignore. To add the files and directory to the .git ignore the file, open the file and type the file name, directory name, and pattern to ignore files and directories. Consider the below image:

Git Ignore

In the above file, I have given one format and a directory to ignore. The above format *.txt will ignore all the text files from the repository, and /newfolder/* will ignore the newfolder and its sub-content. We can also give only the name of any file to ignore.

Step3: Now, to share it on Git, we have to commit it. The .gitignore file is still now in staging area; we can track it by git status command. Consider the below output:

Git Ignore

Now to stage it, we have to commit it. To commit it, run the below command:

  1. $ git add .gitignore  
  2. $ git commit -m "ignored directory created."  

The above command will share the file .gitignore on Git. Consider the below output.

Git Ignore
Git Ignore

Now, we have ignored a pattern file and a directory in Git.

Rules for putting the pattern in .gitignore file:

The rules for the patterns that can be put in the .gitignore file are as follows:

  • Git ignores the Blank lines or lines starting with #.
  • Only the Standard glob patterns work and will be applied recursively throughout the entire working tree.
  • The patterns can be started with a forward slash (/) to avoid recursively.
  • The patterns can be ended with a forward slash (/) to specify a directory.
  • The patterns can be negated by starting it with an exclamation point (!).

Global .gitignore:.

As we know that we can create multiple .gitignore files for a project. But Git also allows us to create a universal .gitignore file that can be used for the whole project. This file is known as a global .gitignore file. To create a global .gitignore, run the below command on terminal:

  1. $ git config --global core.excludesfile ~/.gitignore_global  

The above command will create a global .gitignore file for the repository.

How to List the Ignored Files?

In Git, We can list the ignored files. There are various commands to list the ignored files, but the most common way to list the file is the ls command. To list the ignored file, run the ls command as follows:

  1. $ git ls-files -i --exclude-standard  

Or

  1. $ git ls-files --ignore --exclude-standard  

The above command will list all available ignored files from the repository. In the given command, -I option stands for ignore and --exclude-standard is specifying the exclude pattern. Consider the below output:

Git Ignore

From the above output, we can see that the ls command is listing the available ignored files from the repository.

Git Revert

In Git, the term revert is used to revert some changes. The git revert command is used to apply revert operation. It is an undo type command. However, it is not a traditional undo alternative. It does not delete any data in this process; instead, it will create a new change with the opposite effect and thereby undo the specified commit. Generally, git revert is a commit.

It can be useful for tracking bugs in the project. If you want to remove something from history then git revert is a wrong choice.

Moreover, we can say that git revert records some new changes that are just opposite to previously made commits. To undo the changes, run the below command:

Syntax:

  1. $ git revert   

Git Revert Options:

Git revert allows some additional operations like editing, no editing, cleanup, and more. Let's understand these options briefly:

< commit>: The commit option is used to revert a commit. To revert a commit, we need the commit reference id. The git log command can access it.

  1. $ git revert <commit-ish>  

<--edit>: It is used to edit the commit message before reverting the commit. It is a default option in git revert command.

  1. $ git revert -e <commit-ish>  

-m parent-number /--mainline parent-number: it is used to revert the merging. Generally, we cannot revert a merge because we do not know which side of the merge should be considered as the mainline. We can specify the parent number and allows revert to reverse the change relative to the specified parent.

-n/--no edit: This option will not open a text editor. It will directly revert the last commit.

  1. $ git revert -n <commit-ish>  

--cleanup=<mode>: The cleanup option determines how to strip spaces and comments from the message.

-n/--no-commit: Generally, the revert command commits by default. The no-commit option will not automatically commit. In addition, if this option is used, your index does not have to match the HEAD commit.

The no-commit option is beneficial for reverting more than one commits effect to your index in a row.

Let's understand how to revert the previous commits.

Git Revert to Previous Commit

Suppose you have made a change to a file say newfile2.txt of your project. And later, you remind that you have made a wrong commit in the wrong file or wrong branch. Now, you want to undo the changes you can do so. Git allows you to correct your mistakes. Consider the below image:

Git Revert

As you can see from the above output that I have made changes in newfile2.txt. We can undo it by git revert command. To undo the changes, we will need the commit-ish. To check the commit-ish, run the below command:

  1. $ git log  

Consider the below output:

Git Revert

In the above output, I have copied the most recent commit-ish to revert. Now, I will perform the revert operation on this commit. It will operate as:

  1. $ git revert 099a8b4c8d92f4e4f1ecb5d52e09906747420814  

The above command will revert my last commit. Consider the below output:

Git Revert

As you can see from the above output, the changes made on the repository have been reverted.

Git revert is a command used to create a new commit that undoes the changes introduced by a specific commit. Unlike git reset, which modifies the project history, git revert creates a new commit that effectively cancels out the changes made in the target commit

Git Revert Merge

In Git, merging is also a commit that has at least two parents. It connects branches and code to create a complete project.

A merge in Git is a commit that has at least two parents. It brings together multiple lines of development. In a work-flow where features are developed in branches and then merged into a mainline, the merge commits would typically have two parents.

How to Revert a Merge

Usually, reverting a merge considered a complicated process. It can be complex if not done correctly. We are going to undo a merge operation with the help of git revert command. Although some other commands like git reset can do it. Let's understand how to revert a merge. Consider the below example.

I have made some changes to my file design2.css on the test and merge it with test2. Consider the below output:

Git Revert

To revert a merge, we have to get its reference number. To check commit history, run the below command:

  1. $ git log   

The above command will display the commit history. Consider the below output:

Git Revert

From the above output, copy your merging commit that you to want to revert and run the below command:

  1. $ git revert <commit reference> -m 1  

The above command will revert the merging operation. Here, -m 1 is used for the first parent as the mainline. Merge commit has multiple parents. The revert needs additional information to decide which parent of the merge shall be considered as the mainline. In such cases, the parameter -m is used. Consider the below output:

Git Revert

From the above output, we can see that the previous merge has been reverted.

Git Reset

The term reset stands for undoing changes. The git reset command is used to reset the changes. The git reset command has three core forms of invocation. These forms are as follows.

  • Soft
  • Mixed
  • Hard

If we say in terms of Git, then Git is a tool that resets the current state of HEAD to a specified state. It is a sophisticated and versatile tool for undoing changes. It acts as a time machine for Git. You can jump up and forth between the various commits. Each of these reset variations affects specific trees that git uses to handle your file in its content.

Additionally, git reset can operate on whole commits objects or at an individual file level. Each of these reset variations affects specific trees that git uses to handle your file and its contents.

Git Reset

Git uses an index (staging area), HEAD, and working directory for creating and reverting commits. If you have no idea about what is Head, trees, index, then do visit here Git Index and Git Head.

The working directory lets you change the file, and you can stage into the index. The staging area enables you to select what you want to put into your next commit. A commit object is a cryptographically hashed version of the content. It has some Metadata and points which are used to switch on the previous commits.

Let's understand the different uses of the git reset command.

There are three different kinds of resets in Git, and they all differ based on how they handle the commits that get left hanging. They all rewrite Git history, and they all move the HEAD back, but they deal with the changes differently:

  • git reset --soft
    
    , which will keep your files, and stage all changes back automatically.
  • git reset --hard
    
    , which will completely destroy any changes and remove them from the local directory. Only use this if you know what you're doing.
  • git reset --mixed
    
    , which is the default, and keeps all files the same but unstages the changes. This is the most flexible option, but despite the name, it doesn't modify files.

Git Reset Hard

It will first move the Head and update the index with the contents of the commits. It is the most direct, unsafe, and frequently used option. The --hard option changes the Commit History, and ref pointers are updated to the specified commit. Then, the Staging Index and Working Directory need to reset to match that of the specified commit. Any previously pending commits to the Staging Index and the Working Directory gets reset to match Commit Tree. It means any awaiting work will be lost.

Let's understand the --hard option with an example. Suppose I have added a new file to my existing repository. To add a new file to the repository, run the below command:

  1. $ git add <file name>  

To check the status of the repository, run the below command:

  1. $ git status  

To check the status of the Head and previous commits, run the below command:

  1. $ git log  

Consider the below image:

Git Reset

In the above output, I have added a file named newfile2.txt. I have checked the status of the repository. We can see that the current head position yet not changed because I have not committed the changes. Now, I am going to perform the reset --hard option. The git reset hard command will be performed as:

  1. $ git reset --hard  

Consider the below output:

Git Reset

As you can see in the above output, the -hard option is operated on the available repository. This option will reset the changes and match the position of the Head before the last changes. It will remove the available changes from the staging area. Consider the below output:

Git Reset

The above output is displaying the status of the repository after the hard reset. We can see there is nothing to commit in my repository because all the changes removed by the reset hard option to match the status of the current Head with the previous one. So the file newfile2.txt has been removed from the repository.

There is a safer way to reset the changes with the help of git stash.

Generally, the reset hard mode performs below operations:

  • It will move the HEAD pointer.
  • It will update the staging Area with the content that the HEAD is pointing.
  • It will update the working directory to match the Staging Area.

Git Reset Mixed

A mixed option is a default option of the git reset command. If we would not pass any argument, then the git reset command considered as --mixed as default option. A mixed option updates the ref pointers. The staging area also reset to the state of a specified commit. The undone changes transferred to the working directory. Let's understand it with an example.

Let's create a new file say newfile2.txt. Check the status of the repository. To check the status of the repository, run the below command:

  1. $ git status  

It will display the untracked file from the staging area. Add it to the index. To add a file into stage index, run the git add command as:

  1. $ git add <filename>  

The above command will add the file to the staging index. Consider the below output:

Git Reset

In the above output, I have added a newfile2.txt to my local repository. Now, we will perform the reset mixed command on this repository. It will operate as:

  1. $ git reset --mixed  

Or we can use only git reset command instead of this command.

  1. $ git reset  

The above command will reset the status of the Head, and it will not delete any data from the staging area to match the position of the Head. Consider the below output:

Git Reset

From the above output, we can see that we have reset the position of the Head by performing the git reset -mixed command. Also, we have checked the status of the repository. As we can see that the status of the repository has not been changed by this command. So it is clear that the mixed-mode does not clear any data from the staging area.

Generally, the reset mixed mode performs the below operations:

  • It will move the HEAD pointer
  • It will update the Staging Area with the content that the HEAD is pointing to.

It will not update the working directory as git hard mode does. It will only reset the index but not the working tree, then it generates the report of the files which have not been updated.

If -N is specified on the command line, then the statements will be considered as intent-to-add by Git.

Git Reset Head (Git Reset Soft)

The soft option does not touch the index file or working tree at all, but it resets the Head as all options do. When the soft mode runs, the refs pointers updated, and the resets stop there. It will act as git amend command. It is not an authoritative command. Sometimes developers considered it as a waste of time.

Generally, it is used to change the position of the Head. Let's understand how it will change the position of the Head. It will use as:

  1. $ git reset--soft <commit-sha>  

The above command will move the HEAD to the particular commit. Let's understand it with an example.

I have made changes in my file newfile2.txt and commit it. So, the current position of Head is shifted on the latest commit. To check the status of Head, run the below command:

  1. $ git log  

Consider the below output:

Git Reset

From the above output, you can see that the current position of the HEAD is on f1d4b486f2eeefe575194d51ec3a54926ab05ef7 commit. But, I want to switch it on my older commit 2c5a8820091654ac5b8beed774fe6061954cfe92. Since the commit-sha number is a unique number that is provided by sha algorithm. To switch the HEAD, run the below command:

  1. $ git reset --soft  2c5a8820091654  

The above command will shift my HEAD to a particular commit. Consider the below output:

Git Reset

As you can see from the above output, the HEAD has been shifted to a particular commit by git reset --soft mode.

Git Reset to Commit

Sometimes we need to reset a particular commit; Git allows us to do so. We can reset to a particular commit. To reset it, git reset command can be used with any option supported by reset command. It will take the default behavior of a particular command and reset the given commit. The syntax for resetting commit is given below:

  1. $ git reset <option> <commit-sha>  

These options can be

  • --soft
  • --mixed
  • --Hard




new repo 










u cnt create dir without file
























































merge



delete branch







































Comments

Popular posts from this blog

Teradata

work