Git & Version Control

Chapter 3
Git Installation, Configuration, and Tools

Certificate in DevOps
Git & Version Control   •   Certificate

Git Installation, Configuration, and Tools

Introduction

Git is a distributed version-control system used to record, compare, restore, and coordinate changes to files. In DevOps, Git is more than a developer utility: it is a foundation for automated testing, continuous integration, infrastructure management, release control, and collaborative software delivery. A reliable Git installation and a deliberate configuration reduce avoidable errors before the first commit is created.

This chapter explains how to install Git, establish user identity, select editors and default behaviors, manage line endings and credentials, create SSH keys, define ignore rules, and work through command-line, integrated development environment (IDE), and graphical interfaces. The emphasis is on practical foundations appropriate for certificate-level study, while also introducing the governance and security considerations expected in professional environments.

Learning Objectives

By the end of this chapter, you should be able to:

  • install and verify Git on major operating systems;
  • distinguish system, global, local, and environment-based configuration;
  • configure identity, editors, default branches, aliases, and line-ending behavior;
  • explain HTTPS credentials, credential helpers, and SSH authentication;
  • create appropriate .gitignore rules without hiding important project files;
  • use Git from a terminal, an IDE, and a graphical client;
  • diagnose common installation and configuration problems;
  • apply secure and reproducible configuration practices in a DevOps environment.

1. Git as a Configurable Tool

Git stores project history in a repository. A repository usually contains a hidden .git directory, which holds objects, references, configuration, and metadata. The working tree contains the files being edited. The staging area, also called the index, records the exact content selected for the next commit.

A simplified workflow is:

working tree → staging area → commit → remote repository
     edit          git add       git commit       git push

Git itself is distributed: a clone normally contains the project history needed for local work, rather than requiring every operation to contact a central server. Services such as GitHub, GitLab, and Bitbucket provide hosting, collaboration, access control, and automation, but they are not Git itself.

Configuration controls how Git behaves. Common examples include the author name shown in commits, the program used for commit messages, the default initial branch name, and rules for converting text-file line endings. Configuration is stored in several scopes:

ScopeTypical location or sourceEffect
SystemInstallation-wide configurationApplies to all users on a machine
GlobalUser configuration, commonly ~/.gitconfig or ~/.config/git/configApplies to one user across repositories
Local.git/config inside a repositoryApplies only to one repository
WorktreeWorktree-specific configuration when enabledApplies to one linked worktree
Command or environmentCommand options and variables such as GIT_AUTHOR_NAMEUsually affects one operation or process

When the same setting appears at multiple levels, the more specific setting generally takes precedence over the less specific one. Local configuration therefore overrides global configuration. This layered model is useful, but it can also cause confusion when a value appears to be ignored.

To inspect configuration and its source, use:

git config --list --show-origin --show-scope

To view the effective value of a setting:

git config --get user.name
git config --get user.email

2. Installing and Verifying Git

Windows

Git for Windows can be installed from the official Git project distribution. The installer provides Git Bash, a Unix-like shell, and integrates Git with Windows tools. During installation, users may select a default editor, PATH behavior, and line-ending conversion policy. For most learners, the recommended option is to allow Git to be available from the command prompt and third-party software while retaining Git Bash for practice.

macOS

Git may be installed through the Apple developer command-line tools, a package manager, or the official distribution. A common verification command is:

git --version

If macOS prompts for command-line tools, accepting the installation is usually sufficient for basic Git use.

Linux

Git is normally installed through the operating system package manager. For example, Debian- and Ubuntu-based systems commonly use:

sudo apt update
sudo apt install git

The exact command differs across distributions. Package repositories are generally preferable to downloading unknown binaries because they provide signature, dependency, and update mechanisms managed by the operating system.

Verification

After installation, verify both availability and identity:

git --version
git --help
git config --list --show-origin

A version number confirms that an executable is found, but it does not prove that the PATH points to the intended installation. On systems with multiple installations, use operating-system commands such as where git on Windows or which git on Unix-like systems to identify the executable being used.

3. Establishing Commit Identity

Every commit records an author name and email address. These values identify the person associated with the commit; they do not, by themselves, authenticate the user to a hosting service. A commit identity is therefore different from a login identity.

Set a global identity with:

git config --global user.name "Amina Yusuf"
git config --global user.email "[email protected]"

Check it with:

git config --global --get-regexp '^user\.'

A repository may require a different identity. For example, a consultant may use a client-specific address in one project:

cd client-project
git config user.name "Amina Yusuf"
git config user.email "[email protected]"

The local values override the global values for that repository. Organizations may require verified or privacy-protecting addresses supplied by their Git hosting provider. Users should follow organizational policy and avoid exposing personal addresses in public projects when a managed privacy address is available.

The author and committer fields can differ. Normally Git sets both from the configured identity, but rebasing, automation, or explicit environment variables may produce different values. This distinction matters during audits because the person who originally authored a change may not be the person who committed or integrated it.

4. Editors, Defaults, and Aliases

Choosing an editor

Git opens an editor for commit messages, merges, rebases, and other operations. A user who is unfamiliar with the default terminal editor can configure a preferred program:

git config --global core.editor "code --wait"

The --wait option is important for editors that normally return immediately. Git must wait until the message file is closed before continuing. Other examples include:

git config --global core.editor "nano"
git config --global core.editor "vim"

The correct command depends on the editor installation and operating system.

Default branch name

New repositories historically used names such as master, while many organizations now standardize on main. Configure the initial branch name for repositories created in the future:

git config --global init.defaultBranch main

This setting does not rename an existing branch. An existing branch can be renamed explicitly, for example:

git branch -m master main
git push -u origin main

The remote hosting service and branch-protection rules must also be updated before deleting or redirecting the old branch.

Useful aliases

Aliases shorten frequent commands and can make output consistent:

git config --global alias.st status
git config --global alias.co checkout
git config --global alias.last "log -1 --stat"
git config --global alias.lg "log --oneline --decorate --graph --all"

Aliases should improve clarity rather than conceal risky behavior. A team should document shared aliases, and users should be cautious with aliases that execute shell commands or destructive operations. An alias is not a substitute for understanding the underlying command.

5. Line Endings and Text Normalization

Text files represent the end of a line differently on operating systems. Unix-like systems traditionally use line-feed (LF), while Windows traditionally uses carriage-return plus line-feed (CRLF). Inconsistent handling can make an unchanged file appear to contain changes across platforms.

Git can normalize text in the repository while presenting suitable line endings in each working tree. A common cross-platform configuration is:

git config --global core.autocrlf true

on Windows, and:

git config --global core.autocrlf input

on macOS or Linux. With input, Git converts CRLF to LF when committing but does not convert LF to CRLF when checking out.

Some teams prefer explicit repository rules through .gitattributes:

* text=auto
*.sh text eol=lf
*.bat text eol=crlf
*.png binary

The text attribute identifies text for normalization, eol specifies a working-tree convention, and binary prevents unsuitable text transformations. Repository-level attributes are more reproducible than relying only on personal settings.

Line-ending changes can create large, misleading diffs. Before changing configuration in an existing project, inspect the repository policy and discuss migration with the team. Normalization changes should be committed separately from functional edits where possible.

6. Credentials and Authentication

Git commonly communicates with remote repositories using HTTPS or SSH. Authentication answers the question “who may access this remote?” Authorization then determines what that identity may do.

HTTPS

A hosting service may require a username together with a personal access token (PAT), rather than an account password. Tokens should be created with the minimum scopes needed and should have an expiration date where the provider supports one.

Credential helpers reduce repeated prompts by storing or brokering credentials. Common approaches include:

  • operating-system keychains or credential managers;
  • Git Credential Manager;
  • memory-only caching for temporary use;
  • plaintext storage, which is generally unsuitable for sensitive credentials.

Inspect the configured helper with:

git config --show-origin --get-all credential.helper

Never commit a PAT, password, private key, or cloud access token into a repository. If a secret is exposed, revoke or rotate it immediately; deleting the line in a later commit does not remove it from all historical objects or clones.

SSH

SSH uses a key pair: a private key retained by the user and a public key uploaded to the hosting service. The private key must remain confidential. A typical modern key-generation command is:

ssh-keygen -t ed25519 -C "[email protected]"

The command creates a private key and a corresponding public key, commonly under ~/.ssh. Protect the private key with a strong passphrase. The public key, whose filename usually ends in .pub, may be added to the hosting account.

Start an SSH agent when required and load the key:

ssh-add ~/.ssh/id_ed25519

Test access to a provider using its documented host name, for example:

ssh -T [email protected]

The first connection may display a host-key fingerprint. Verify the fingerprint through a trusted provider source before accepting it. This protects against connecting to an impersonating host. SSH configuration can select a particular key:

Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519
    IdentitiesOnly yes

The remote URL determines the protocol. It may be inspected or changed with:

git remote -v
git remote set-url origin [email protected]:team/project.git

SSH improves authentication convenience but does not automatically provide authorization. Account permissions and repository policies remain decisive.

7. Ignore Rules and Repository Hygiene

A .gitignore file specifies untracked files that Git should normally disregard. Typical entries include build output, dependency directories, local environment files, logs, editor metadata, and operating-system artifacts:

# Dependencies
node_modules/

# Build output
dist/
build/

# Local configuration and secrets
.env
.env.*

# Logs
*.log

# Editor and operating-system files
.vscode/
.DS_Store

Patterns may be global, repository-level, or directory-specific. A global ignore file is useful for personal operating-system files, while project-specific dependencies and build artifacts belong in the repository’s .gitignore so that all contributors share the rule.

Important pattern behavior includes:

  • a trailing slash matches a directory;
  • *.log matches names ending in .log according to Git’s pattern rules;
  • a leading ! negates a previous pattern, subject to directory traversal rules;
  • a leading slash anchors a pattern relative to the directory containing the ignore file.

Ignored files are not automatically removed if they have already been tracked. To stop tracking a file while retaining it locally, use:

git rm --cached .env
git commit -m "Stop tracking local environment file"

Use git check-ignore -v path/to/file to determine which rule is responsible for an ignored path. Avoid ignoring files merely because they are inconvenient. Source code, dependency lock files, deployment manifests, and documentation often need to be versioned. The correct question is whether the file is generated, machine-specific, sensitive, or otherwise unsuitable for collaborative history.

8. Three Ways to Use Git

Command line

The command line exposes the complete Git model and is the most portable interface for automation and troubleshooting. A minimal workflow is:

git init
printf "# Demo\n" > README.md
git add README.md
git commit -m "Add README"
git status
git log --oneline

git status should be used frequently. It reports the current branch, staged changes, unstaged changes, and untracked files. git diff compares working-tree changes, while git diff --cached examines staged changes.

IDE integration

Modern IDEs display changed files, inline differences, branches, staging controls, commit forms, and conflict markers. IDE integration improves discoverability and reduces context switching, but the underlying operations remain Git commands. Users should understand whether a button stages all files, stages selected lines, commits staged content, or performs a commit-and-push sequence.

IDE terminals are especially useful for combining visual review with precise commands. Configure the IDE to use the same Git executable and identity as the system terminal, and verify behavior when multiple installations exist.

Graphical clients

Standalone clients provide history graphs, side-by-side diffs, staging interfaces, branch management, and visual conflict resolution. They can be helpful for reviewing complex histories and teaching collaboration concepts. However, graphical tools vary in terminology and may hide important details such as force pushes, rebases, or credential behavior. Before confirming a destructive operation, inspect the proposed command and target branch.

The interfaces are complementary. A professional user should be able to move from a GUI to the command line when diagnosing an error, and should be able to use visual diff tools when they improve review accuracy.

9. A Practical Configuration Sequence

A dependable setup can follow this sequence:

  1. Install Git from a trusted source.
  2. Run git --version and identify the executable path.
  3. Configure global name and email.
  4. Select the editor and default initial branch.
  5. Establish an organization-approved line-ending policy.
  6. Configure an approved credential helper or SSH key.
  7. Clone a test repository and inspect git config --list --show-origin.
  8. Create a small commit and review its identity and diff.
  9. Add project-specific .gitignore and .gitattributes rules.
  10. Record team conventions in project documentation.

A configuration file can be inspected directly, but editing it manually requires care. Prefer git config commands for routine changes because they handle section and key syntax correctly.

Illustrative Case: Configuring Git for a Cross-Platform DevOps Team

Background

A five-person team develops a web service. Two members use Windows, two use Linux, and one uses macOS. The project includes JavaScript dependencies, shell scripts, generated build files, and a local .env file containing development settings.

Problem

Pull requests show thousands of apparent line changes after a Windows contributor edits a shell script. The .env file is accidentally staged, and a new team member cannot push because the hosting service no longer accepts account passwords over HTTPS.

Analysis

The team has three separate issues: inconsistent line-ending policy, incomplete ignore rules, and outdated authentication expectations. These should not be treated as one undifferentiated Git problem. Line endings affect content presentation and diffs; ignore rules affect file selection; authentication affects remote access.

Approach and Solution

The team adds the following .gitattributes file:

* text=auto
*.sh text eol=lf
*.ps1 text eol=crlf
*.png binary

It adds a reviewed .gitignore containing node_modules/, dist/, .env, and local editor artifacts. The team verifies that dependency lock files remain tracked. Windows users configure core.autocrlf true, while Unix-like users use core.autocrlf input, with repository attributes providing the shared rule.

Each member configures a verified commit identity. The new member creates an Ed25519 SSH key protected by a passphrase and uploads only the public key. The remote URL is changed from HTTPS to SSH. The team documents the setup in CONTRIBUTING.md and asks every member to inspect staged changes with git diff --cached before committing.

Outcome

New shell-script edits produce stable LF content in the repository, generated files no longer appear as candidate changes, and the .env file is excluded before it can be staged. The team member can authenticate without a reusable account password. Existing files with problematic history are normalized in a dedicated, reviewed commit.

Learning Points

The case demonstrates that Git configuration is part of engineering design. Repository-level rules create shared behavior, personal settings support local environments, and security controls must be managed separately from convenience features. A successful configuration is reproducible, documented, and tested rather than assumed to be correct because Git launches successfully.

10. Troubleshooting, Governance, and Best Practice

Common problems

“Git is not recognized.” The executable is absent or not on PATH. Confirm installation and inspect the executable location.

The wrong identity appears in a commit. Check local configuration, global configuration, environment variables, and the commit’s author and committer fields. Use git config --list --show-origin --show-scope.

A file is ignored unexpectedly. Run git check-ignore -v filename; a global ignore file may be responsible.

A secret remains visible after adding it to .gitignore. Ignore rules affect untracked files only. Remove the file from tracking and rotate the exposed secret if it was committed.

A push is rejected. Check the remote URL, authentication method, account permission, branch protection, and whether the remote contains commits not present locally.

A diff shows every line changed. Investigate line endings, encoding, and formatting tools before merging. Do not blindly accept a large diff.

Security and governance

Configuration should follow least privilege. Tokens should have limited scopes, SSH keys should have passphrases, and credentials should be stored in approved managers. Private keys and secrets should never be placed in .gitconfig, shell history, source code, issue comments, or build logs.

Organizations should document naming conventions, approved remote hosts, branch policies, signing requirements, secret-scanning procedures, and retention expectations. Commit signing can help verify that a commit was produced by a holder of a particular cryptographic key, but signing does not prove that the content is correct or that the author is trustworthy. Authentication, authorization, review, and automated testing remain separate controls.

Git configuration can also be automated through workstation-management tools and development containers. Automation improves consistency, but configuration scripts must avoid embedding secrets and should be tested across operating systems. AI coding tools and IDE assistants may create files, modify ignore rules, or suggest commands; users remain responsible for reviewing those changes, especially commands involving credentials, history rewriting, or force pushing.

Chapter Summary

Git installation is complete only when the executable, PATH, identity, editor, defaults, authentication method, and repository conventions work together. Configuration is layered: system, global, local, worktree, command, and environment settings may interact, with more specific settings generally overriding broader ones. Commit identity identifies authorship but is distinct from hosting authentication.

Editors, default branch names, aliases, line-ending rules, and attributes affect everyday reliability. HTTPS credential helpers and SSH keys provide different authentication mechanisms, both of which require careful secret handling. .gitignore prevents unsuitable untracked files from entering candidate changes, but it does not remove files already tracked. Command-line, IDE, and graphical interfaces expose the same underlying Git model with different strengths. Professional practice combines convenience with inspection, documentation, least privilege, and explicit review of staged content.

Key Terms

Git: A distributed version-control system.

Repository: A directory and its Git metadata containing project history.

Working tree: The checked-out files currently available for editing.

Staging area: The index containing content selected for the next commit.

Commit: A recorded snapshot with metadata and a parent-history relationship.

Remote: A named reference to another repository location.

Configuration scope: The level at which a Git setting applies.

Global configuration: User-wide settings applied across repositories.

Local configuration: Settings applying to one repository.

Commit identity: The author and committer name and email stored in commits.

Alias: A custom shorthand for a Git command.

Line ending: The character sequence marking the end of a text line.

.gitattributes: A repository file defining path attributes such as text normalization.

.gitignore: A pattern file identifying untracked paths Git should normally ignore.

Credential helper: A mechanism for storing, retrieving, or brokering authentication data.

Personal access token: A scoped token used instead of a password for some HTTPS services.

SSH key pair: A private and public key used for cryptographic authentication.

Host-key fingerprint: A value used to verify the identity of an SSH server.

Least privilege: Giving users and tools only the access they require.

Review Questions

Short Answer Questions

  1. What is the difference between global and local Git configuration?
  2. Why should an editor command sometimes include a --wait option?
  3. What problem does .gitattributes help solve?
  4. Why does adding a tracked secret to .gitignore not remove it from history?
  5. What is the difference between a private SSH key and its corresponding public key?

Long Answer Questions

  1. Explain the layered Git configuration model and describe how a learner could diagnose a conflicting setting.
  2. Compare HTTPS authentication using a personal access token with SSH-key authentication, including security practices for each.
  3. Explain how line endings can produce misleading diffs and propose a cross-platform repository policy.
  4. Discuss the strengths and limitations of command-line, IDE, and graphical Git interfaces.
  5. Design a Git setup procedure for a new DevOps team, including identity, editor, branch, credentials, ignore rules, and documentation.

Analytical / Application Questions

  1. A repository contains .env, node_modules/, shell scripts, generated documentation, and source code. Which items should normally be ignored, which should be tracked, and what additional questions would you ask before deciding?
  2. A contributor reports that every line in a file changed after a pull request, although only two lines were edited. Develop a diagnostic sequence using Git configuration, attributes, diff inspection, and file encoding checks.
  3. A team discovers that a cloud token was committed two days ago and later removed. Identify the immediate security actions and the Git-history actions required to reduce continuing exposure.

Multiple Choice Questions with Answers

Question 1

Which command displays Git configuration values together with their source files and scopes?

A. git status --show-origin

B. git config --list --show-origin --show-scope

C. git remote --verbose --scope

D. git log --config-source

Correct Answer: B. git config --list --show-origin --show-scope

Question 2

Which configuration normally applies only to the current repository?

A. System configuration

B. Global configuration

C. Local configuration

D. Shell profile configuration

Correct Answer: C. Local configuration

Question 3

What is the main purpose of core.editor?

A. To select the program Git opens for messages

B. To encrypt repository objects

C. To select the remote hosting service

D. To format source-code indentation

Correct Answer: A. To select the program Git opens for messages

Question 4

Which file is intended for repository-level line-ending and text attributes?

A. .gitmodules

B. .gitattributes

C. .gitcredentials

D. README.git

Correct Answer: B. .gitattributes

Question 5

What happens when a file already tracked by Git is added to .gitignore?

A. It is automatically deleted from every clone

B. It is immediately removed from the repository index

C. It remains tracked unless explicitly removed from tracking

D. Its contents are encrypted

Correct Answer: C. It remains tracked unless explicitly removed from tracking

Question 6

Which item should normally remain secret?

A. An SSH public key

B. A repository URL

C. A Git alias

D. An SSH private key

Correct Answer: D. An SSH private key

Question 7

Which command identifies the ignore rule responsible for a path?

A. git check-ignore -v path/to/file

B. git inspect-ignore path/to/file

C. git status --why-ignored path/to/file

D. git rule-show path/to/file

Correct Answer: A. git check-ignore -v path/to/file

Question 8

What is the purpose of git diff --cached?

A. To compare two remote repositories

B. To inspect staged changes

C. To delete untracked files

D. To display SSH fingerprints

Correct Answer: B. To inspect staged changes

Question 9

Which statement about commit identity is correct?

A. It is identical to hosting-service authentication

B. It records author and committer metadata in the commit

C. It grants permission to push to every remote

D. It replaces the need for access control

Correct Answer: B. It records author and committer metadata in the commit

Question 10

Why is --wait useful when configuring an external editor for Git?

A. It makes Git wait until the editing operation is complete

B. It waits for network authentication indefinitely

C. It delays all future commits by one minute

D. It prevents line-ending conversion

Correct Answer: A. It makes Git wait until the editing operation is complete

Git & Version Control
Chapter 3 of 14