Ultimate Git Handbook

Astrogeek
10 min readSep 9, 2023

--

Git is an important tool for every developer, especially if you are working with designs, graphics, and application versions and want to keep track of every version and related changes.

Git lets you do just that and more, you can keep track of every change to potentially any file on your system, revert to an older version in case of an issue, etc. All this with just a little overhead.

This Git Ultimate Handbook covers almost all commonly used commands and those with special use cases.

Important Links

Installation & GUIs

With platform-specific installers for Git, GitHub also provides the ease of staying up-to-date with the latest releases of the command line tool while providing a graphical user interface for day-to-day interaction, review, and repository synchronization.

GitHub for Windows

https://windows.github.com

GitHub for Mac

https://mac.github.com

For Linux and Solaris platforms, the latest release is available on the official Git website.

Git for All Platforms

https://git-scm.com

Git Setup

SETUP Configuring user information used across all local repositories

First, introduce yourself to git. That means we tell git our name and email address. Please use “FirstName LastName” and name@domain.org email address. This is needed because every Git commit uses this information. The information is added to the commits you start creating. You need to do this only once (when using the --global option).

git config --global user.name "[firstname lastname]"

Set a name that is identifiable for credit when reviewing the version history git

config --global user.email "[valid-email]"

Set an email address that will be associated with each history marker

Note — You must use a working, non-trash email address to submit patches. Also, pick one that is long-lived so that people can contact you later. An @ipfire.org email address is not required for patch submission. You can of course use your own private git repository.

git config --global color.ui auto

Set automatic command line coloring for Git for easy reviewing

Setting up Git for email

git config --global sendemail.smtpencryption ssl
git config --global sendemail.smtpserver submissions.ipfire.org
git config --global sendemail.smtpserverport 465
git config --global sendemail.smtpuser USERNAME

Check the git config settings

To check the configuration settings use the --list option to list the above settings.

git config --list

SETUP & INIT

Configuring user information, initializing and cloning repositories

git init

Initialize an existing directory as a Git repository

git init is one way to start a new project with Git. To start a repository, use either git init or git clone - not both.

To initialize a repository, Git creates a hidden directory called .git. That directory stores all of the objects and refs that Git uses and creates as a part of your project's history. This hidden .git directory is what separates a regular directory from a Git repository

git clone [url]

Retrieves an entire repository from a hosted location via a URL.

The git clone command is used to create a copy of a specific repository or branch within a repository.

Git is a distributed version control system. Maximize the advantages of a full repository on your machine by cloning.

Some Important terms

Version Control

Version Control is a system that tracks changes to a file or a set of files, which enables you to switch to any older version at any time. Version Control lets track modified files, which user made which changes, compare timelines, and revert back to the last safe version in case of any issue or screw-up.

Git

Git is a DevOps tool used for source code management. It is a free and open-source version control system that handles small to huge projects efficiently. Git is used to track changes in the source code, enabling multiple developers to work together on non-linear development.

Git Commands

Let’s move on to our main section and list different types of git commands and their use case scenarios.

Staging, Snapshot, and Commit

git status

Show modified files in the working directory, stage for your next commit.

When in doubt, run git status. This is always a good idea. The git status command only outputs information, it won't modify commits or changes in your local repository.

A useful feature of git status is that it will provide helpful information depending on your current situation.

git add [file]

The git add command adds new or changed files in your working directory to the Git staging area.

git add is an important command - without it, no git commit would ever do anything. Sometimes, git add can have a reputation for being an unnecessary step in development. But in reality, git add is an important and powerful tool. git add allows you to shape history without changing how you work.

git add <path>: Stage a specific directory or file

git add .: Stage all files (that are not listed in the .gitignore) in the entire repository

git add -p: Interactively stage hunks of changes

You can see all of the many options with git add in git-scm's documentation.

git reset [file]

unstaged a file while retaining the changes in the working directory

git diff

It runs a diff function on Git data sources. These data sources can be files, branches, commits, and more. It is used to show changes between commits, commit, working tree, etc.

It compares the different versions of data sources. The version control system stands for working with a modified version of files. So, the diff command is a useful tool for working with Git.

However, we can also track the changes with the help of the git log command with option -p. The git log command will also work as a git diff command.

git diff --staged

diff of what is staged but not yet committed

git commit -m "[descriptive message]"

git commit creates a commit, which is like a snapshot of your repository. These commits are snapshots of your entire repository at specific times. You should make new commits often, based around logical units of change. Over time, commits should tell a story of the history of your repository and how it came to be the way that it currently is. Commits include lots of metadata in addition to the contents and message, like the author, timestamp, and more.

BRANCH & MERGE

Isolating work in branches, changing context, and integrating changes

A branch is a version of the repository that diverges from the main working project. It is a feature available in most modern version control systems. A Git project can have more than one branch. These branches are a pointer to a snapshot of your changes. When you want to add a new feature or fix a bug, you spawn a new branch to summarize your changes. So, it is complex to merge the unstable code with the main code base, and also facilitates you to clean up your future history before merging with the main branch.

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

Switch to another branch and check it out in your working directory

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

The advantage of a version control system is that it records changes. These records allow us to retrieve data like commits, and figure out bugs, and updates. But, all of this history will be useless if we cannot navigate it. At this point, we need the git log command.

Git log is a utility tool to review and read the history of everything that happens to a repository. Multiple options can be used with a git log to make history more specific.

Generally, the git log is a record of commits. A git log contains the following data:

  • A commit hash is a 40-character checksum data generated by SHA (Secure Hash Algorithm) algorithm. It is a unique number.
  • Commit Author metadata: The information of authors such as author name and email.
  • Commit Date metadata: It’s a date timestamp for the time of the commit.
  • Commit title/message: It is the overview of the commit given in the commit message.
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 between what is in branchA and what is not in branchB

git show [SHA]

Show any object in Git in a human-readable format

TRACKING PATH CHANGES

Versioning file removes and path changes

In Git, the term rm stands for remove. It is used to remove individual files or a collection of files. The key function of git rm is to remove tracked files from the Git index. Additionally, it can be used to remove files from both the working directory and staging index.

The files being removed must be ideal for the branch to remove. No updates to their contents can be staged in the index. Otherwise, the removal process can be complex, and sometimes it will not happen. But it can be done forcefully by the -f option.

git rm [file]

Delete the file from the project and stage the removal for the commit

git mv [existing-path] [new-path]

Change an existing file path and stage the move

git log --stat -M

Show all commit logs with the indication of any paths that moved

SHARE & UPDATE

Retrieving updates from another repository and updating local repos

If you try running git remote -v in your repositories, you'll probably see something called origin. You may notice origin in many messages from Git. origin is the human-friendly name for the URL where the remote repository is stored. It's like a key-value pair, and origin is the default.

You may need or want to work with multiple remotes for one local repository. This can be common in open source when a contributor needs to create a fork of a repository to have permission to push changes to the remote.

In this case, it’s common to create and clone a fork. Then, the default remote would be origin, of the fork. To make it easier to pull any changes to update the local copy of the fork from the original repository, many people add the original repository as a remote. It's typical to name this remote upstream.

git remote add [alias] [url]

Add a remote git URL as an alias

git remote -v

List the current remotes associated with the local repository

git remote remove [name]

Remove a remote origin

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

reset is the command we use when we want to move the repository back to a previous commit, discarding any changes made after that commit.

Rebasing in Git is a process of integrating a series of commits on top of another base tip. It takes all the commits of a branch and appends them to the commits of a new branch.

The main aim of rebasing is to maintain a progressively straight and cleaner project history. Rebasing gives rise to a perfectly linear project history that can follow the end commit of the feature to the beginning of the project without even forking. This makes it easier to navigate your project.

git rebase [branch]

apply any commits of the current branch ahead of the specified one

git reset --hard [commit]

clear staging area, rewrite the working tree from the specified commit

TEMPORARY COMMITS

Temporarily store modified, tracked files to change branches

Sometimes you want to switch the branches, but you are working on an incomplete part of your current project. You don’t want to make a commitment to half-done work. Git stashing allows you to do so. The git stash command enables you to switch branches without committing to the current branch.

The below figure demonstrates the properties and role of stashing concerning the repository and working directory.

Generally, the stash’s meaning is “store something safely in a hidden place.” The sense in Git is also the same for stash; Git temporarily saves your data safely without committing.

Stashing takes the messy state of your working directory and temporarily saves it for further use.

git stash

Save modified and staged changes

git stash save "<Stashing Message>"

Stash will be saved with the stash message

git stash list

List stack order of stashed file changes

git stash apply

You can re-apply the changes that you just stashed by using the git stash command. To apply the commit, use the git stash command, followed by the apply option.

git stash apply <stash id>

In case of more than one stash, you can use the “git stash apply” command followed by stash index id to apply the particular commit.

git stash show

The above command will show the files that are stashed and the changes made to them.

git stash pop

Write working from the top of the stash stack

git stash drop

Discard the changes from the top of the stash stack

IGNORING PATTERNS

Preventing unintentional staging or committing of files

git config --global core.excludesfile [file]

System-wide ignore pattern for all local repositories

Conclusion

I have tried to list different git commands one can find a use case for, I have missed any feel free to contact me or comment below. Also, I have explained every command to the best of my knowledge, if you find any error be sure to convey it.

Thanks for taking the time to read the blog and have a happy coding day.

--

--