Git Fundamentals
Git Fundamentals: Study Notes
What Git Does
Git is a distributed version control system (VCS). A VCS records changes to a project over time so that developers can inspect its history, identify who made changes and when, and return to earlier versions when necessary.
A Git project’s history is stored in a repository. With version control, developers can:
Keep a record of how a project has changed.
Recover earlier versions after an unwanted change.
Work on the same project and combine contributions.
Create checkpoints as work progresses.
Without version control, people may try to preserve project history by copying whole folders. This becomes inefficient as projects grow and difficult to coordinate when several people need to work on the same code.
Centralized and distributed version control
Centralized systems keep the main project history on a central server. Team members connect to that server to obtain code and share changes. Subversion and Microsoft Team Foundation Server are examples.
The server is a single point of failure: if it is unavailable, team members may be unable to collaborate or save changes to the shared system.
Distributed systems give each team member a copy of the project and its history. This allows work and snapshots to be recorded locally. If a central server is unavailable, team members can still work and may be able to synchronize directly with one another.
Git and Mercurial are examples.
Git is widely used because it is free, open source, fast, and scalable. Branching and merging—ways to work on separate lines of development and later combine them—are particularly efficient in Git.
Ways to Use Git
Git can be used through a command-line interface (CLI), a code editor or IDE, or a dedicated graphical user interface (GUI).
Command line
The command line lets users run Git commands in a terminal or command prompt. It is available in many environments, including remote servers where a GUI may not be installed or permitted. It also supports Git features that some graphical tools may not expose.
Editors and graphical tools
Many editors and IDEs provide common Git features. Dedicated GUI applications offer visual ways to inspect history, compare changes, and manage repositories. These tools can make some tasks easier to understand, but their feature sets may be limited.
A practical approach is to use the tool that best fits the task: command-line commands, editor features, and GUIs can complement one another. Understanding the command line remains useful even when a GUI is preferred for everyday work.
On Windows, Git Bash provides a terminal environment that behaves more like Unix or Linux shells than the built-in Windows command prompt.
Installing Git and Getting Help
Check whether Git is installed
Open a terminal or command prompt and run:
git --versionThe command displays the installed Git version. If Git is not installed, or an older version is needed, it can be installed using the instructions for the relevant operating system.
Find command documentation
Git provides both detailed and concise help:
git config --help
git config -h--helpopens detailed documentation, which can be navigated in a terminal pager and exited by pressingq.-hdisplays a shorter summary of options.
Searching for a command’s documentation is another way to learn what its options do.
Git Configuration
Git settings can be defined at three levels:
System level: applies to all users of the computer.
Global level: applies to all repositories belonging to the current user.
Local level: applies only to the current repository.
When settings conflict, the more specific repository-level setting generally takes precedence over broader settings.
Set a name and email
Git uses author information in commits. A user can set their global name and email with:
git config --global user.name "Your Name"
git config --global user.email you@example.comQuotes are needed when a value contains spaces.
Choose a default editor
Git may open an editor when a longer commit message is needed. The example below sets Visual Studio Code as the global editor:
git config --global core.editor "code --wait"The --wait option makes the terminal wait until the editor window is closed. The code command must be available in the system path for this setting to work.
To open the global configuration file in the configured editor, use:
git config --global -eThe file is organized into sections, such as user and core.
Handle line endings
Line endings differ between operating systems:
Windows commonly uses a carriage return and a line feed.
macOS and Linux commonly use a line feed.
Git’s core.autocrlf setting helps keep line endings consistent when Windows and Unix-like systems share a repository:
git config --global core.autocrlf trueOn Windows, true tells Git to convert line endings when checking files out and to normalize them when storing changes. On macOS or Linux, the usual setting is:
git config --global core.autocrlf inputWith input, Git normalizes line endings when storing files but does not add Windows-style carriage returns when checking them out. Consistent handling reduces unexpected line-ending changes in shared projects.
Creating a Repository
A repository is the Git-managed history for a project. To start tracking a project, move to its directory and initialize Git:
git initGit creates a hidden .git directory inside the project directory. This directory contains the repository’s internal data and history. It is an implementation detail: users generally should not edit or delete its contents manually. Removing .git removes the repository history, even though the project’s ordinary files may remain.
Git does not automatically track every existing file when a repository is initialized. Files must be added to the staging area before Git includes them in a commit.
The Three Main Areas in Git
Git’s everyday workflow involves three areas:
Working directory (working tree): the project files currently being edited.
Staging area (index): the proposed contents of the next commit.
Repository: the committed project history.
A commit records the staged state as a project snapshot. The staging area allows changes to be reviewed and selected before they become part of that snapshot.
Basic workflow
Edit, add, rename, or delete files in the working directory.
Stage the changes that should be included in the next commit.
Review the staged changes.
Commit them with a meaningful message.
The staging area is not simply an empty temporary space that disappears after every commit. After a commit, it represents the state recorded by that commit. When a file is changed in the working directory, the staged version remains unchanged until the new version is staged.
For example, if a file is staged and then edited again, Git has one version in the staging area and a newer version in the working directory. Staging the file again updates the proposed snapshot.
Staging and Committing Changes
Check the repository status
Use git status to see which files are untracked, modified, or staged:
git statusUntracked files are not yet under Git’s tracking. Staged changes are included in the proposed next commit. Unstaged changes exist in the working directory but have not been added to that proposal.
Add files to the staging area
The git add command stages files:
git add file1.txt
git add file1.txt file2.txt
git add *.txt
git add .A filename stages that file.
Multiple filenames can be supplied.
A pattern can select matching files.
git add .stages changes in the current directory and its subdirectories.
Before staging an entire directory, it is worth checking whether it contains generated, large, or otherwise unnecessary files.
Staging records the file’s current contents in the index. If the file is edited again afterward, the later edits are not staged until it is added again.
Create a commit
A commit records the staged project state in the repository:
git commit -m "Initial commit"A commit message identifies what the snapshot represents. For a longer explanation, running git commit without -m opens the configured editor. A useful message typically starts with a short summary, followed by a blank line and any necessary detail. Comment lines inserted by Git in the message file are ignored.
Each commit has a unique identifier and records information such as its author, date, message, and project snapshot.
Bypassing the staging area
For tracked files, the -a option can stage modifications and deletions as part of a commit:
git commit -am "Fix sign-up validation"This skips the separate staging step for those changes. It does not include new, untracked files. Because staging makes it possible to inspect and select changes, it is generally better to stage and review changes explicitly, especially when a commit should include only some of the work.
Commit Practices
A useful commit is a meaningful checkpoint in the project’s development.
Keep commits focused: each commit should represent one logically separate change, such as a bug fix or a typo correction.
Avoid commits that are too small: committing after every trivial edit produces a history full of uninformative entries.
Avoid commits that are too large: waiting until many unrelated changes accumulate makes it harder to review the work and recover from mistakes.
Commit at meaningful checkpoints: the goal is a useful history, not a fixed number of commits per day.
Write informative messages: messages should explain the change clearly enough to help future readers understand the project history.
Use a consistent wording convention: many teams write messages in the present tense or imperative form, such as “Fix the sign-up bug.” Consistency across a team matters more than choosing one particular convention.
Keeping each commit focused makes its message easier to write and makes the history more useful to both the original developer and collaborators.
Removing and Renaming Files
Remove a file
A regular filesystem removal affects the working directory, but Git may still have the file in the staging area. For example:
rm file2.txt
git add file2.txtStaging the deletion tells Git that the file should be absent from the next commit.
Git’s own removal command combines removal from the working directory and staging area:
git rm file2.txtAfter staging a deletion, committing records that the file was removed from the project snapshot.
Rename or move a file
A filesystem move or rename changes the working directory, but Git must also be told about the resulting deletion and new path. One approach is to stage both changes. Git can often recognize the relationship as a rename.
The Git command performs the move and stages it in one operation:
git mv old-name.txt new-name.txtThe rename can then be included in a commit. Git detects renames by comparing file content and history; a rename is not simply a separate kind of stored file content.
Ignoring Files
A project often contains files that should not be shared or committed, such as logs, compiled output, or local temporary files. A project-level .gitignore file lists paths and patterns Git should ignore.
For example:
logs/
*.log
*.classlogs/ignores a directory namedlogs.*.logignores files matching that pattern.*.classcan exclude generated Java class files.
The .gitignore file should normally be placed in the project’s root directory and committed so the same rules apply to collaborators. Lines beginning with # are comments.
Ignoring does not untrack existing files
Ignore rules apply to files Git is not already tracking. If a file has already been committed, adding it to .gitignore does not stop Git from reporting later changes to it. To retain a file in the working directory while removing it from Git’s index, use:
git rm --cached -r bin/The --cached option removes the path from the index without deleting the working copy, and -r applies recursively to a directory. The removal should then be committed. Afterward, matching files can be ignored by the relevant rule.
Short Status and Reviewing Changes
Short status format
For a compact status display, use:
git status -sThe output uses two status columns:
Left column: status in the staging area.
Right column: status in the working directory.
Common indicators include:
M: modified.A: added.??: untracked.
For example, a modification shown only in the right column is in the working directory but has not been staged. A staged modification appears in the left column. If a file is edited after staging, it can have a staged change in the left column and an additional unstaged change in the right column.
Inspect differences with git diff
The git diff command compares file contents between Git areas:
git diff
git diff --stagedgit diffcompares the working directory with the staging area, showing unstaged changes.git diff --stagedcompares the staging area with the latest commit, showing changes proposed for the next commit.
Diff output commonly marks removed lines with - and added lines with +. The header identifies the files being compared, and a hunk header gives the line ranges shown. A newly added file has no earlier version in the commit, so its diff shows only added content.
Reviewing the staged diff before committing helps catch accidental, incomplete, or unrelated changes. A visual diff tool can make comparisons easier to inspect, while understanding text diffs remains useful in terminals and other environments.
Undoing Changes Safely
Git provides different ways to undo staged changes, discard working-directory edits, and remove untracked files. These actions affect different areas, so the intended target should be checked before running them.
Unstage a change
To remove a file’s changes from the staging area while keeping the working copy, use:
git restore --staged file1.jsBy default, this restores the staged version from the current commit. For a newly added file that has no version in the current commit, unstaging removes it from the index and leaves it as an untracked file in the working directory.
Discard unstaged changes
To discard working-directory edits and restore the file to the version in the staging area, use:
git restore file1.jsThis overwrites the file’s unstaged edits. If the file has staged changes, those staged changes are retained; the working copy is reset to match the staged version.
Remove untracked files
git restore cannot recover or discard an untracked file using a previous Git version, because Git has no tracked version of it. To remove untracked files, use:
git clean -fTo include untracked directories, use:
git clean -fdThis is a potentially destructive operation: untracked files removed this way may not be recoverable through Git. The force option is required because Git treats this cleanup as risky.
Restore a file from an earlier commit
The source version can be specified explicitly. For example, to restore a file from the commit before the current one:
git restore --source=HEAD~1 -- file1.jsThis places the selected historical version in the working directory; it does not itself create a commit. If the file is absent from the current commit, the restored copy may appear as an untracked file. The resulting state can then be reviewed, staged, and committed if appropriate.
Viewing Commit History
List commits with git log
The git log command displays commit history, usually from newest to oldest:
git logA full log entry includes the commit identifier, author, date, and message. If the output spans multiple pages, the pager can be navigated with the space bar and exited with q.
Useful options include:
git log --oneline
git log --oneline --reverse--onelineshows a short identifier and one-line message.--reversereverses the usual ordering, displaying earlier commits first.
Commit identifiers and references
A commit identifier is a hexadecimal hash. Git can often identify a commit using only a sufficiently long, unambiguous prefix of that hash.
HEAD is a reference to the current position in the repository—normally the current branch’s latest commit. HEAD~1 refers to the commit one step before HEAD; larger numbers move further back along that history.
A branch is a named line of development. Repositories can have multiple branches, allowing separate features or fixes to be developed independently and later combined.
Inspect a commit with git show
Use git show to inspect a commit:
git show HEAD
git show HEAD~1The output includes commit information and, by default, a diff showing what changed in that commit. A commit can be specified by its identifier or by a reference such as HEAD~1.
To display the version of a particular file stored in a commit, use a commit reference followed by a colon and the file path:
git show HEAD~1:.gitignoreThis shows that file’s content at that historical point rather than a comparison of changes.
List files in a commit with git ls-tree
Git represents directory structures as trees. To inspect the top-level entries of a commit, use:
git ls-tree HEAD~1The output identifies entries such as files and directories, along with their object types and identifiers. Adding -r lists entries recursively.
Git’s object types include:
Blob: represents file content.
Tree: represents a directory and references its contents.
Commit: records a project snapshot and metadata such as its parent, author, and message.
Tag: names or annotates a particular point in history.
A commit stores a complete logical snapshot of the project. Git is efficient about storage: identical file contents can be reused rather than duplicated, and object data is compressed. This lets Git move quickly between snapshots without requiring users to calculate every intermediate change.
Choosing a Comparison Tool
Git’s text-based diff is useful in a terminal, while visual diff tools can make it easier to see how one version differs from another. Many modern editors and IDEs provide built-in comparisons of staged and unstaged changes.
Git can be configured to launch a visual diff tool. For example, the following configuration names Visual Studio Code as the tool and provides a command for launching comparisons:
git config --global diff.tool vscode
git config --global difftool.vscode.cmd "code --wait --diff $LOCAL $REMOTE"The placeholders refer to the two versions being compared. Once configured, git difftool can open the visual comparison; git difftool --staged can compare staged changes with the latest commit. Configuration details can vary by operating system and editor setup.
Key Workflow Summary
A common sequence for recording a focused change is:
Inspect the current state with
git status.Edit files in the working directory.
Stage the intended changes with
git add.Review the staged changes with
git diff --staged.Create a commit with a clear message using
git commit.
Git’s core model is built around commits as project snapshots and the staging area as the place to select the next snapshot. Understanding how those areas differ makes it easier to track work, review changes, and undo the right action.

Ask anything
We've read this whole study set, so questions about it get the best answers.