Module 0.6: Git Basics — Track Your Work
Complexity:
[MEDIUM]- Long-form foundational read with git drillsTime to Complete: 90–120 minutes (long-form beginner read + git drills)
Prerequisites: Module 0.5: Editing Files
What You’ll Be Able to Do
Section titled “What You’ll Be Able to Do”After completing this module, you will be able to:
- Diagnose repository state by interpreting
git status,git diff, andgit logoutput instead of guessing what Git will save. - Construct focused commits by moving selected file changes from the working directory into the staging area and then into repository history.
- Implement a safe local Git setup with deliberately chosen author identity, a new repository, and an ignore policy for generated files and secrets.
- Compare local and remote repository timelines so you can choose when to clone, push, pull, fetch, or pause for conflict resolution.
- Design a small Git workflow for Kubernetes configuration files that produces reviewable history without leaking credentials or generated artifacts.
Why This Module Matters
Section titled “Why This Module Matters”Hypothetical scenario: an operations group keeps Kubernetes manifests on a shared drive because everyone can open the folder quickly, edit YAML, and copy the latest files into a deployment script. One morning the production namespace changes in a way nobody expected, the cluster accepts the update, and the team cannot tell whether the current file is the intended version, a half-finished experiment, or a copy of an older configuration. The outage investigation is slow not because Kubernetes is mysterious, but because the team has no trustworthy timeline for the text files that describe its infrastructure.
Git solves that operational problem by turning ordinary files into a deliberate, reviewable history. It records snapshots, authors, messages, and parent relationships, so a team can compare what changed, why it changed, and when the change entered the shared record. That matters for source code, but it matters just as much for cloud-native work: a Deployment, a Namespace, a Terraform module, or a CI pipeline definition can all change production behavior when automation trusts the repository as the source of truth.
This module starts with local Git because local confidence comes before collaboration. You will initialize a repository, configure identity, stage changes intentionally, read diffs before committing, and use a .gitignore file to keep noise out of history. By the end, you should not merely remember a list of commands; you should be able to diagnose what Git is about to do and explain whether the next action should be git add, git commit, git pull, git push, or no action at all.
That diagnostic mindset is what separates a useful Git user from someone who only knows a happy-path recipe. A recipe works when every file is exactly where the tutorial expects it to be, but engineering work rarely stays that neat. You may have half-finished edits, generated logs, a teammate’s new remote commits, or a local file that must never leave your machine. Git gives you precise tools for each case, and this module teaches you to choose among them based on observed state.
How Git Thinks About Your Files
Section titled “How Git Thinks About Your Files”Git is often described as version control, but beginners sometimes hear that phrase and imagine a cloud backup tool that continuously syncs the latest file contents. That model leads to mistakes, because Git is not trying to mirror every keystroke to a server. Git records deliberate snapshots when you ask it to, keeps those snapshots in a local database, and lets you decide exactly which changes belong together before they become part of the project history.
Think of Git like a manual save system in a strategy game. You can explore, make a risky move, inspect the result, and decide whether that state deserves a save point. If you save at thoughtful moments, later decisions become easier because you can compare states and explain how you moved from one state to the next. If you save everything randomly, the history exists, but it does not help you reason during a review or incident.
Historically, many version control systems were centralized. A central server held the authoritative history, and clients depended on that server to inspect history or create new commits. Git is distributed: by default, a clone receives the repository’s history, not just the latest files; options such as shallow or partial cloning change what is transferred. You can inspect available commits, compare versions, and create local commits while offline, then synchronize with a remote when connectivity and team coordination are available.
The practical result is that Git has two personalities. Locally, it is a fast database and comparison engine for your files. Collaboratively, it is a synchronization protocol that lets multiple people exchange histories through a remote such as GitHub, GitLab, or Bitbucket. Good Git habits come from respecting both personalities: make clean local commits first, then share them only after you have checked what they contain.
This local-first design is especially helpful in cloud-native work because many infrastructure changes need careful review before they touch a cluster. You can edit manifests, compare the patch, commit a narrow change, and ask another engineer to review the branch without applying anything to Kubernetes yet. Git does not validate the cluster behavior for you, but it gives the team a stable object to discuss. A reviewer can point to a line, a commit, or a branch instead of relying on a vague description of what changed.
Git manages your files through three logical areas. The names matter because most confusing Git messages are simply Git telling you which area contains a change. Your working directory is where your editor writes files, the staging area is where you assemble the next snapshot, and the repository is the saved history inside the hidden .git database. The staging area is the piece many beginners skip, but it is what lets you turn messy work into a clean commit.
+---------------------+ +---------------------+ +---------------------+| | | | | || Working Directory | ----> | Staging Area | ----> | Repository || (Your local files) | | (The loading dock) | | (The saved history) || | | | | |+---------------------+ +---------------------+ +---------------------+ | | | | 1. Modify files | | |---------------------------->| | | | 2. Group changes | | |---------------------------->| | | | | | |<----------------------------------------------------------| 3. Restore old versionsThe working directory is the current project folder on disk. When you edit namespace.yaml, create a README, or delete a temporary file, you are changing the working directory. Git can detect that tracked files differ from the last commit, and it can also notice new untracked files, but it will not automatically decide that those changes belong in the next snapshot. This is why git status is the first diagnostic command to learn.
The staging area, also called the index, is a deliberate selection of what the next commit will contain. You can stage one file while leaving another modified file unstaged, or even stage only some hunks from a file with more advanced commands later. That separation is valuable when real work is messy. A debugging session might touch authentication, deployment YAML, and local notes, but the commit should capture one coherent reason for change.
In the ordinary repository you will initialize for this practice, .git holds the local repository database where commits live. Other repository layouts can place that data elsewhere. A commit records a snapshot of file contents, author and committer metadata with timestamps, a message, and zero or more parent pointers; the first commit has none. In common repositories, each commit is named by a hash such as a SHA-1 object identifier, and newer Git versions can also support SHA-256 repositories. The important beginner idea is simpler than the cryptography: if the content or metadata changes, the identifier changes too.
Pause and predict: you fixed a database connection bug in db.py, but while searching for it you also added temporary print statements to auth.py and api.py. Which part of Git lets you save only the real fix while keeping the temporary debug code on disk? Decide which area of Git you would use and which exact command moves only the intended file before opening the reveal.
Check your prediction
The staging area (or index) lets you save only the real fix while keeping the temporary debug code on disk. It decouples the files you are still editing from the files you are ready to save as the next snapshot. You can run git add db.py and commit only that file, while leaving auth.py and api.py as unstaged modifications in your working directory until you are ready to clean them up.
Configure Git and Create a Repository
Section titled “Configure Git and Create a Repository”Git is a command-line tool at its core, even when teams use graphical clients or web interfaces around it. Platform engineers must be comfortable with the terminal version because many workflows happen over SSH, inside automation logs, or on machines where a graphical client is unavailable. The goal is not to memorize every option. The goal is to become fluent enough that repository state is visible instead of mysterious.
Start by checking that Git is installed. The hands-on tasks and selected local examples were checked with Git 2.53.0 on 2026-11-02; the Git 2.56.0 release commit pins the documentation used below. Other versions may lack commands or options used here; consult your installed version’s documentation or update Git before continuing. If Git is missing, follow the official installation guide.
git --versionExpected output should include the Git version installed on your machine; the exact number may differ from this example.
git version 2.56.0Before creating commits, configure the identity Git will place into commit metadata. This is not the same thing as authenticating to GitHub during a push. The name and email configured here answer the question, “Who authored this snapshot?” Remote authentication proves an identity; the host’s permissions separately decide whether that identity may push. Keeping those concepts separate prevents confusion when a commit succeeds locally but a push later asks for credentials.
First inspect the existing identity without changing it. An unset value may print nothing and return a nonzero status; the disposable repositories below will receive their own local training identity before you commit.
# Read your configured namegit config --get user.name
# Read your configured email addressgit config --get user.emailThe --global flag changes account-wide configuration, usually in ~/.gitconfig; this lesson does not change it. After successful initialization, --local writes only to that repository. The deliberately fictional training identity below is for disposable local commits, not publication. For real work, choose your author identity and email deliberately: commit metadata includes the email. For example, in that repository you could set git config --local user.name "Your Name" and git config --local user.email "your-chosen-email@example.com", replacing the placeholders. See Git’s identity setup.
Choose a practice directory under your control, outside a real work repository. Start a disposable child Bash with the following command alone and wait for its prompt before pasting the entire grouped setup below. The prompt may look like your previous prompt. Stay in that child for the theory practice; when finished, type exit to return to its parent shell.
bash --noprofile --norcThe group stops this child if setup fails. If it exits, STOP: do not paste later commands into the parent shell. Leave any existing k8s-webapp file, directory, or symlink untouched; choose an unused name consistently or retry in another practice location with a new child shell. The five cleared Git location selectors and root checks guard this setup’s location; they do not sandbox every environment setting.
{set -etrap 'printf "%s\n" "STOP: setup failed; do not continue in the parent shell."' EXITunset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_OBJECT_DIRECTORY GIT_COMMON_DIRmkdir k8s-webappcd ./k8s-webapppractice_dir=$(pwd -P)git init --initial-branch=maintest "$(git rev-parse --show-toplevel)" = "$practice_dir"test "$(git rev-parse --absolute-git-dir)" = "$practice_dir/.git"git config --local user.name "KubeDojo Learner"git config --local user.email "learner@example.invalid"printf 'Practice repository ready: %s\n' "$practice_dir"trap - EXITset +e}Example output confirms that Git created an empty repository database in a hidden .git directory. Your path will differ.
Initialized empty Git repository in /home/alex/k8s-webapp/.git/Practice repository ready: /home/alex/k8s-webappWhat exactly changed? Git created a hidden .git directory inside k8s-webapp. That hidden directory is not decorative; it is the repository database for this project. It contains objects, references, local configuration, and the machinery Git uses to know which branch you are on. If you delete .git, your current files may remain on disk, but the local history, branches, and repository identity are gone.
# List all files, including hidden onesls -laExample output shows the hidden .git directory beside the current and parent directory entries. Names, dates, and sizes will differ.
total 12drwxr-xr-x 3 alex alex 4096 Oct 12 10:00 .drwxr-xr-x 5 alex alex 4096 Oct 12 09:59 ..drwxr-xr-x 7 alex alex 4096 Oct 12 10:00 .gitBefore running the next command in any new repository, make a habit of predicting what state you expect Git to report. You just ran git init --initial-branch=main inside an empty folder and have not created any files yet. What exact branch state, commit count, and staging status should git status output? Commit to your prediction before revealing the answer.
Check your prediction
In a brand-new repository with no tracked files and no commits, git status reports that you are on branch main, that there are “No commits yet”, and that there is “nothing to commit (create/copy files and use “git add” to track)”. That prediction habit is more valuable than it sounds, because every later Git recovery task starts by comparing expected state with observed state.
Build Commits Deliberately
Section titled “Build Commits Deliberately”The command you will use most often is git status, because it is a way to ask Git what it sees. It reports the branch and staged, unstaged, and untracked changes by comparing local working files, the index, and the current commit; it may refresh Git’s internal index cache. Any ahead/behind comparison uses your local upstream record, which can be stale until a fetch updates it. Treat status as your compass before staging, committing, pulling, or pushing.
There is another subtle reason git status matters: it teaches you Git’s vocabulary in context. “Untracked” means a file is not in the index and is not ignored. “Changes not staged” means the working file differs from its indexed copy. “Changes to be committed” means the index differs from the last commit. Those messages are a compact state report.
Create the first file in the practice repository. This file defines a Kubernetes Namespace, which is a simple object that lets us focus on Git behavior without needing a running cluster. The content is valid YAML, but the point is the workflow: write a file, inspect repository state, stage the file, and commit the staged snapshot with a message that explains the intent. You can write the file using the cat heredoc below, or open nano namespace.yaml (practiced in Module 0.5) if you prefer editing in an interactive editor.
cat << 'EOF' > namespace.yamlapiVersion: v1kind: Namespacemetadata: name: webapp-prodEOFRun git status immediately. New learners often skip this because they believe they already know what changed, but memory is a weak audit system. Git reports the local state it can see; reporting options and ignore rules affect what appears. Read the output before deciding what to stage.
git statusThe output should classify the new file as untracked because it exists on disk but is not part of the next snapshot.
On branch main
No commits yet
Untracked files: (use "git add <file>..." to include in what will be committed) namespace.yaml
nothing added to commit but untracked files present (use "git add" to track)The file is untracked, which means Git sees it in the working directory but it is not in the index. Untracked files are not part of the next commit. Once you stage the file, Git can compare later working-file edits with its indexed copy. This behavior lets notes, generated artifacts, and local test files stay outside a commit unless you select them.
Move the file into the staging area with git add. This command is easy to underestimate because it sounds like you are adding a file to Git forever. More precisely, you are adding the current content of that file to the staging area for the next commit. If you edit the file again after staging, the new edit will be unstaged until you add it too.
git add namespace.yamlRun git status again and compare the wording. The file has moved from “Untracked files” to “Changes to be committed.” That wording tells you the next commit will include the file as it existed when you staged it. The content is staged, but you have not created a commit for it yet.
git statusThe output should now show the file under changes to be committed, which means it is staged.
On branch main
No commits yet
Changes to be committed: (use "git rm --cached <file>..." to unstage) new file: namespace.yamlCommit the staged change. The message should explain the reason for the snapshot at a level useful to a future reviewer. A message like “update” forces people to inspect the diff just to understand the intent. A message like “feat: add production namespace definition” gives the reader a quick summary and still lets them open the diff for detail when needed. The feat: prefix is an optional commit-message convention, not Git syntax.
git commit -m "feat: add production namespace definition"For this first commit, normal output can show a root-commit label, the commit subject, and a change summary with the number of inserted lines. The object ID and output can differ; quiet mode suppresses the summary. See the Git 2.56 commit documentation.
[main (root-commit) a1b2c3d] feat: add production namespace definition 1 file changed, 4 insertions(+) create mode 100644 namespace.yamlCheck status after the commit. With normal untracked-file reporting, a clean status means Git reports no staged or unstaged tracked changes and no non-ignored untracked files. Configured options can hide untracked files, and ignored files can still exist. Clean does not mean the project is correct, secure, or ready for production.
git statusThe output should now report a clean working tree because the staged content has been committed.
On branch mainnothing to commit, working tree cleanPause and predict: while testing locally, an engineer places a real access token into a YAML file, confirms the application starts, and immediately runs git commit -am "test config" before pushing to a shared repository. If they delete the token in a second commit ten minutes later, is the credential safe? Commit to your analysis and determine what operational steps must follow before opening the reveal.
Check your prediction
No. Deleting the token in a later commit does not remove it from earlier history. If pushed, promptly revoke or rotate it with its provider and follow the repository’s incident process. History cleanup cannot remove other people’s copies. For a local-only commit, stop before pushing and follow the credential response steps; assess any other exposure with the owner.
Before staging, ask whether the patch has one reason that a reviewer can evaluate. Before committing, ask whether the staged content is the exact content you want attached to the message. Before pushing, ask whether the branch contains only work you are ready to share. Answer these questions before moving to the next operation.
Now modify the Namespace by adding a label. Labels can identify and select Kubernetes objects; controllers and tools can use them. The Git workflow remains the same: make the change, inspect the difference, stage only the intended content, and commit a focused snapshot.
cat << 'EOF' > namespace.yamlapiVersion: v1kind: Namespacemetadata: name: webapp-prod labels: environment: productionEOFA branch is a line of development whose name points to its latest commit and moves as you commit. HEAD normally refers to the current branch and thus its latest commit; the working tree starts from that commit and can contain later edits. See the Git glossary.
Before staging, read the diff. Plain git diff compares working files with the index, showing unstaged changes. Here nothing is staged, so it also reflects the edit since the last commit; use git diff HEAD to compare the working tree with that commit even when changes are staged. Read the patch before deciding what belongs in the next snapshot.
git diffThe output should show only the new label lines as additions, with surrounding unchanged YAML for context.
diff --git a/namespace.yaml b/namespace.yamlindex e46b825..8394c41 100644--- a/namespace.yaml+++ b/namespace.yaml@@ -2,3 +2,5 @@ apiVersion: v1 kind: Namespace metadata: name: webapp-prod+ labels:+ environment: productionDiff output has a compact grammar. The --- and +++ lines name the old and new sides of the comparison. The chunk header beginning with @@ tells Git and the reader where in the file the change appears. Lines that begin with a space are context, lines beginning with + are additions, and lines beginning with - are removals. A modified line is represented as one removal and one addition, which is why line-by-line review is more precise than “I changed the file.”
When you review a diff for infrastructure files, read it like a deployment plan, not like a spelling check. An image tag change can select a different image; a replica count change can affect availability. Labels can affect which objects a selector matches. The outcome depends on the workload and its rollout, so inspect what each changed field controls.
Pause and predict: imagine the next diff is an excerpt from spec.template.spec.containers in a Deployment. It omits other required fields and is not a complete manifest. Decide whether this is a new field, a deleted field, or a changed value, and describe the possible operational effect before opening the reveal.
@@ -14,3 +14,3 @@ containers: - name: web- image: nginx:1.14+ image: nginx:1.24Check your prediction
The image value changed from nginx:1.14 to nginx:1.24. A Deployment’s Pod template specifies the image for its Pods; the result depends on the rollout, registry, and runtime. In a real review, check whether the target image exists and whether the workload was tested. See the Kubernetes Deployment example.
After confirming the label change is the intended change, stage it with git add namespace.yaml. Once staged, running plain git diff produces no output because there are no unstaged modifications left in the working directory. To review what is currently waiting in the staging area for the next commit, run git diff --staged (or its synonym git diff --cached). This gives you a final pre-commit safety check before recording the snapshot.
git add namespace.yamlgit diff --stagedThe staged diff output confirms that the environment label is queued for the next snapshot, while surrounding lines provide contextual reference for reviewers reading the patch:
diff --git a/namespace.yaml b/namespace.yamlindex e46b825..8394c41 100644--- a/namespace.yaml+++ b/namespace.yaml@@ -2,3 +2,5 @@ apiVersion: v1 kind: Namespace metadata: name: webapp-prod+ labels:+ environment: productionNotice that the commit message should be specific to the label. It does not say “fix stuff” or “update namespace” because those messages decay quickly when someone is scanning history during an incident. A commit message is a tiny piece of operational documentation attached to the exact patch it describes.
git commit -m "chore: add environment label to namespace"Inspect History and Diagnose State
Section titled “Inspect History and Diagnose State”Once a repository has more than one commit, history becomes a diagnostic tool. git log shows the timeline of snapshots, newest first by default, including commit identifiers, author information, dates, and messages. During troubleshooting, this lets you answer who changed something recently and what explanation they left. During code review, it lets you assess whether the branch history tells a coherent story.
History is most useful when commits are small enough to inspect and messages are specific enough to search. If a branch contains one giant commit that changes namespaces, deployments, scripts, and documentation together, reverting or reviewing it becomes risky because every concern is tangled. If the branch contains focused commits, you can inspect the deployment change separately from the documentation change. Git does not force that discipline, but it rewards it every time you need to reason under pressure.
git logThis illustrative output shows the most recent commit first, followed by the earlier root commit. The hashes and dates are examples; the author matches the disposable training identity.
commit 9f8e7d6c5b4a39281716151413121110abcdef12 (HEAD -> main)Author: KubeDojo Learner <learner@example.invalid>Date: Thu Oct 12 10:45:12 2023 -0400
chore: add environment label to namespace
commit a1b2c3d4e5f60718293a4b5c6d7e8f9012345678Author: KubeDojo Learner <learner@example.invalid>Date: Thu Oct 12 10:15:30 2023 -0400
feat: add production namespace definitionThe long hexadecimal strings are commit identifiers. In many repositories they are SHA-1 object names, commonly displayed as long hashes and shortened in user interfaces when the short prefix is unambiguous. You do not need to calculate the hash yourself, but you should recognize it as a precise handle for a snapshot. Saying “the namespace label commit” is helpful in conversation; using the commit identifier is how tools inspect or compare the exact commit.
For daily use, the compact log format is easier to scan. The --oneline option shows abbreviated commit identifiers and subjects on one line each. This is often enough when you want to verify that the expected commits exist in the expected order before pushing a branch or asking someone for review.
git log --onelineThe compact output should preserve the same order while reducing each commit to a short identifier and subject.
9f8e7d6 chore: add environment label to namespacea1b2c3d feat: add production namespace definitionYou can also use git log -p to inspect commit patches. That is useful when the question is not only “When did this change?” but “What exact lines did this commit add or remove?” By default, merge commits do not show a patch; options such as --diff-merges or --first-parent change how merge differences are shown. As repositories grow, you will learn more targeted history tools, but status, diff, and log already give you a strong diagnostic loop: current state, uncommitted line changes, and committed timeline.
Use that loop before assuming Git is broken. If a commit seems to be missing, check whether the change was ever staged and committed. If an ignore rule seems not to work, check whether the file is already tracked or the pattern matches. If a push is rejected, check whether the remote moved ahead of your local branch.
The most important habit is to read these commands as a set. If git status says a file is modified, git diff explains the unstaged modification. If the working tree is clean but behavior changed recently, git log tells you which commits to inspect. If a file is untracked, no amount of git commit will include it until you stage it. The tool is consistent; confusion usually comes from asking the wrong tree the right question.
Pause and predict: you just ran git commit -m "chore: add environment label to namespace" in your practice repository and have not edited any files since. What exact message do you expect git status to output when you run it right now? Commit to an answer before opening the reveal.
Check your prediction
If you have not edited or created any files since the commit, git status will output nothing to commit, working tree clean, subject to the reporting caveats above. If the result differs from your expectation, inspect the state before making another commit.
Work With Remotes Without Losing the Plot
Section titled “Work With Remotes Without Losing the Plot”Everything so far has happened on your local machine. That is enough to practice Git, but it is not enough for team work or backup. A remote is another repository, often hosted on a network service such as GitHub, GitLab, or Bitbucket; a local filesystem path can also be a remote. It is another repository your local repository can fetch from and push to when the histories are compatible.
+-----------------------+ +-----------------------+| | | || Local Repository | | Remote Repository || (Your Laptop) | | (GitHub/GitLab) || | | || commit C (HEAD) | ==== git push ===> | commit C || commit B | | commit B || commit A | <=== git pull ==== | commit A || | | |+-----------------------+ +-----------------------+When you create an empty repository on a hosting platform, the platform gives you a URL. You connect your local repository to that URL with git remote add. By convention, the first and primary remote is named origin, but the name is just a local nickname. The URL is where data goes; the remote name is how you refer to that URL in commands.
# Example command (do not run unless you have a real repository URL prepared)git remote add origin https://github.com/yourusername/k8s-webapp.gitIf the repository already exists on the server, do not create a new local repository and try to glue the histories together. Use git clone <url> instead. Cloning initializes the local .git directory, downloads the repository history, checks out a working tree, and records the remote as origin. Most professional work starts from cloning because the team history already exists before you arrive.
Pushing uploads your local commits to the remote branch. The first push of a new branch often includes -u, which sets an upstream tracking relationship: the upstream is the default branch to integrate from, and future git push and git pull commands can infer the remote branch. Check that the destination and branch relationship match your intention before sharing work.
# Example only: requires your own prepared remote and branchgit push -u origin mainPull combines fetching with integration. First inspect your working state and the remote history. origin/main is a local remote-tracking ref: it records the remote branch as of its last update, not a live view of the server. Fetch refreshes it without integrating it into your current branch; the server can move again afterward. These commands illustrate a prepared remote named origin with a main branch; do not run them against someone else’s repository.
# Example only: requires your own prepared remote and branchgit statusgit fetch origingit log --oneline HEAD..origin/maingit log --oneline origin/main..HEADgit diff HEAD...origin/mainThe first log lists commits reachable from the fetched origin/main but not from HEAD; the second lists local-only commits. A merge base is a best common ancestor of the two commits. The three-dot diff compares the merge base with origin/main, showing changes on the fetched side since the histories met; it is not a direct comparison of the two tips. The initial status can show stale ahead/behind counts until you fetch. See Git’s merge-base documentation.
A fast-forward moves a branch to a descendant commit without creating a merge commit. Histories diverge when each branch has commits missing from the other; integrating them cannot be a fast-forward of either branch. See the Git glossary.
When histories diverge, choose an integration method with your team. git pull --no-rebase origin main merges; git pull --rebase origin main replays local commits on the fetched branch and changes their IDs. Keep this rebase workflow for unshared local commits. git pull --ff-only origin main refuses if a fast-forward is impossible. Git 2.56 documents fast-forward-only as the default; an unconfigured plain pull therefore refuses divergent branches. Configuration and other versions can change that behavior. Ensure your working state is ready before integrating. See the Git 2.56 pull documentation and diff documentation.
Pause and predict: you made two local commits while offline, and a colleague pushed three commits to the same remote branch before you reconnected. What happens if you try git push origin main immediately? Decide what Git will do and what your recovery sequence should be before opening the reveal.
Check your prediction
The push can be rejected because the remote contains work missing locally; the rejection may say fetch first or non-fast-forward, depending on the situation. See the Git 2.56 push documentation. Fetch and inspect both histories, then choose an agreed merge or rebase, resolve any conflicts, verify the result, and retry the push. Fetching alone does not integrate the histories.
Git can detect conflicting edits, but it cannot decide the correct business or operational outcome. A normal non-fast-forward push is rejected, while a force push can move the shared branch away from a teammate’s commit. Agree on the intended change before resolving a conflict or forcing a push.
There is also a difference between remote synchronization and deployment. Pushing a manifest to a repository shares code with the team and may trigger automation if the project has CI/CD configured, but Git itself is not Kubernetes and does not apply resources to a cluster. Git provides a version record; compare it with deployment records and live cluster state to determine what was applied, and use separate checks and reviews to assess safety.
Ignore Noise and Protect Secrets
Section titled “Ignore Noise and Protect Secrets”Real projects generate files that do not belong in version control. Build directories, logs, local cache files, operating system metadata, editor swap files, downloaded dependencies, Terraform state, and private environment files can appear beside source files. Decide which belong in history before staging, and handle any real credential exposure with its owner.
Git handles this with .gitignore, a plain text file usually stored at the repository root. Each line is a pattern for files Git should ignore when they are untracked. The “untracked” part is crucial: matching tracked files remain tracked. For a real credential, respond to exposure and inspect history using the credential response steps; an ignore rule alone does not remove earlier commits.
Credential response
Section titled “Credential response”If a credential was pushed, promptly revoke or rotate it with its provider and follow the repository’s incident process. For any exposure, involve the credential owner. See GitHub’s sensitive-data guidance.
For this course, stop before pushing. With the repository owner, identify the last trusted shared commit: its hash is the base for privately inspecting git log -p <base>..HEAD. Replace <base> with that agreed hash; do not paste sensitive output into tickets or chat. If you cannot establish the base and exposure, the range contains a merge commit, or the credential appears in an older commit, stop and ask the owner or an experienced teammate for help.
Only when the credential occurs in the latest unpushed commit, choose the matching correction:
- If that commit added a whole private file such as
.env, usegit rm --cached .envto keep the local file while removing it from the index. Add a narrow.envignore rule and stage.gitignore. - If the credential is inside a file that should remain tracked, replace it with a placeholder and stage that named file.
Inspect git diff --staged for the intended correction and unrelated staged changes, then use git commit --amend --no-edit. Inspect the commits to share again before pushing. The replaced commit can remain in your local repository, including through the reflog, and on other branches or tags that contain it; amend does not erase those copies. Ask for help if other refs contain the credential. See Git’s amend documentation and reflog reference.
Create an ignore file for the practice repository. The exact patterns below are intentionally small so you can reason about them. They show operating system noise, local secrets, a local kubeconfig-style file, and Terraform state. In a production repository, you would adapt patterns to the tools actually used by the project and review them just like any other infrastructure policy.
cat << 'EOF' > .gitignore# Ignore operating system generated files.DS_StoreThumbs.db
# Ignore local secret and credential files.envsecret-keys.yamlkubeconfig-local
# Ignore terraform state files (if we add Infrastructure as Code later)*.tfstate*.tfstate.backup.terraform/EOFGit reads ignore patterns and normally hides matching untracked files from git status. That reduces the chance of a broad staging command pulling in local-only files. It does not eliminate the need to read git status and git diff, because ignore files can be incomplete and because tracked files remain tracked even if their names later match an ignore rule.
Pause and predict: with the .gitignore file configured above containing *.tfstate, secret-keys.yaml, and kubeconfig-local, which of these three new untracked files would still appear when you run git status: main.tfstate, secret-keys.yaml, or secret-keys.txt? Commit to your prediction for each file before opening the reveal.
Check your prediction
Of those three files, only secret-keys.txt will show up as untracked under git status. The newly created .gitignore may also appear if it has not been staged or committed. main.tfstate is ignored because it matches the *.tfstate wildcard pattern, and secret-keys.yaml is ignored because it matches the exact filename pattern. The file secret-keys.txt does not match any rule in .gitignore, so Git reports it as an untracked candidate ready to be staged.
Now consider a late ignore rule. You committed database-creds.txt last week, then today you add that filename to .gitignore and edit the file. Git will still report the modification because the file is already tracked. To stop tracking the file while keeping the local copy, use an index-only removal such as git rm --cached database-creds.txt, followed by a commit. This does not erase earlier history. If a real credential was pushed, rotate or revoke it; for local-only history, stop before pushing and follow the credential response steps.
This is why a strong Git workflow is both technical and behavioral. The technical controls are .gitignore, git status, git diff, and secret scanning on the server side. The behavior is slower and more deliberate: do not stage blindly, do not store real credentials in practice manifests, and do not assume a later cleanup commit erases exposure. Git history is useful because it remembers, and that same remembering makes leaked secrets persistent.
For Kubernetes and cloud projects, a useful .gitignore policy usually appears before the first serious commit. Local kubeconfig files, generated manifests, temporary logs, Terraform working directories, and downloaded tool caches can all accumulate quickly. Some of those files are harmless noise, while others may contain credentials or environment-specific state. Ignoring them early keeps reviews focused on source files and reduces the chance that a local workstation detail becomes part of the team’s permanent history.
Patterns & Anti-Patterns
Section titled “Patterns & Anti-Patterns”Git patterns are useful when they make history easier to review and safer to automate. The common thread is intentionality: stage intentionally, commit one coherent change at a time, and keep generated or sensitive files out of the repository. The anti-patterns below usually come from speed pressure, but they create slower recovery later because the history stops answering operational questions.
| Pattern or Anti-Pattern | When It Appears | Why It Matters | Better Habit |
|---|---|---|---|
| Pattern: inspect before staging | Any change to code, YAML, scripts, or docs | You catch accidental edits, debug output, and secrets before they enter history. | Run git status, then git diff, then stage named files. |
| Pattern: focused commits | A task touches several files for different reasons | Reviewers can understand and revert one logical change without dragging unrelated work along. | Commit the namespace change separately from README edits or local experiments. |
Pattern: repository-root .gitignore | A project has generated files, logs, state files, or local credentials | Shared ignore policy prevents common local noise from appearing for every contributor. | Review ignore patterns with the same care as build or deployment configuration. |
| Anti-pattern: broad staging by reflex | A learner types git add . after every edit | Git may stage files the learner forgot existed, including generated files or local configuration. | Use named files first; use broad staging only after reading status and diff carefully. |
| Anti-pattern: vague commit messages | A branch has messages such as “update” or “fix” | Incident review becomes slower because history no longer explains intent. | Write a short subject that names the operational reason for the snapshot. |
| Anti-pattern: treating pull as harmless | A local branch has uncommitted work and the remote moved | Pull may create conflicts or merge commits before the learner understands local state. | Start with git status; commit, stash, or discard local work deliberately before integrating remote history. See Git’s pre-merge checks. |
Decision Framework
Section titled “Decision Framework”When Git feels confusing, choose the next command based on the state you need to inspect or change, not based on a memorized sequence. The same repository may need different commands depending on whether the problem is untracked files, unstaged edits, staged changes, missing remote commits, or a branch that has not been pushed before. This table gives you a beginner decision path that is conservative enough for infrastructure work.
| Situation | Safer First Question | Command to Start With | What You Do Next |
|---|---|---|---|
| You edited files and want to know what Git sees | Which tree contains the change? | git status | Read whether files are untracked, unstaged, or staged. |
| You want to review exact line changes | What would surprise a reviewer? | git diff | Stage only the intended files after reading the patch. |
| You already staged changes but want to inspect staged content | What is in the next snapshot? | git diff --staged | Commit if it is correct, or unstage and revise. |
| You want a local save point | Does the staged change have one coherent reason? | git commit -m "message" | Write a message that explains intent, not just mechanics. |
| You need work from the remote | Has my local branch got uncommitted work? | git status then git fetch origin | Inspect the fetched ref and choose how to integrate. |
| You need to share local commits | Does the remote have work I lack? | git push or explicit git push -u origin main | If rejected, inspect the error and fetched history before integrating and retrying. |
Use git init when you are starting a brand-new local repository in a directory that does not already have history. Use git clone when the project already exists somewhere else and you want your local copy to share that existing history. Use .gitignore before local files pile up, especially when a project touches credentials or generated artifacts. Use git log when behavior changed and you need a timeline, not when you are trying to inspect uncommitted edits.
The decision framework also helps you avoid destructive commands early in your Git journey. There are commands that rewrite history, discard changes, or remove files from the index, and you will learn some of them later. At this stage, prefer observation commands first. A clean diagnosis with status, diff, and log makes recovery commands safer because you know exactly which state you are trying to change.
Did You Know?
Section titled “Did You Know?”- Git began in 2005. The Linux kernel community’s free BitKeeper arrangement ended, and the project developed a distributed replacement. Pro Git’s history describes the context.
- The name is intentionally cheeky. The Git project README includes a playful explanation of the name.
- Object identifiers are part of Git’s integrity model. Git supports SHA-1 and SHA-256 repositories; the Git 2.56 documentation notes they do not currently interoperate.
Common Mistakes
Section titled “Common Mistakes”| Mistake | Why It Happens | How to Fix It |
|---|---|---|
| Accidentally committing a password or secret | The learner stages broadly without reading git status and git diff, so a local .env or credential file enters the commit. | If pushed, revoke or rotate it and follow the incident process. For local-only history, stop before pushing and follow the credential response steps; an ignore rule does not remove history. |
| Seeing “fatal: refusing to merge unrelated histories” | A repository was initialized locally, while the hosting service also created its own first commit such as a README. | Prefer cloning an existing remote. If combining histories is truly intended, use the explicit unrelated-histories option only after reviewing why the histories differ. |
| Getting “updates were rejected” during push | The remote branch may have commits the local branch lacks. | Inspect the error, fetch and compare histories, then choose how to integrate before retrying. |
| Writing empty or meaningless commit messages | The learner treats commits as checkpoints for themselves rather than messages to future maintainers. | Amend an unpushed commit message when needed and practice explaining the operational reason for each snapshot. |
| Forgetting to stage files before committing | The working directory contains changes, but the staging area is empty when git commit runs. | Run git status, stage the intended files with git add <file>, inspect again, and retry the commit. |
| Committing generated or binary artifacts | Build outputs and logs sit beside source files, and the repository has no ignore policy yet. | To stop tracking a file while keeping its local copy, use git rm --cached -- <file>, review and commit the cleanup, and add a suitable .gitignore pattern. See the history caveat. |
| Adding an ignore rule after a file is already tracked | The learner expects .gitignore to override history for files already committed. | Remove the file from tracking with an index-only removal such as git rm --cached <file> and commit that change. If a real credential was pushed, revoke or rotate it; for local-only history, stop before pushing and follow the credential response steps. |
1. Your team deployed a Kubernetes configuration and behavior changed immediately. You need to identify the recent commits, authors, and messages before deciding what to inspect next. Which Git command gives you the timeline, and why is it the right starting point?
Use git log to inspect local commit IDs, authors, dates, and messages. git log --oneline is a compact hash-and-subject scan and does not show authors. git status describes workspace and index state; plain git diff compares working files with the index. To identify a deployed change, establish the deployed revision and inspect an up-to-date fetched ref as appropriate; local history alone cannot prove what was deployed.
2. You modified service.yaml and ran git commit -m "expose port 8080", but Git said nothing was added to commit. What state did you forget to change, and how should you recover?
The file was still in the working directory and had not been moved into the staging area. Git does not automatically include every modified file in a commit, because the staging area is where you choose the next snapshot’s contents. Run git status to confirm the file state, then git add service.yaml, inspect status again, and rerun the commit. This preserves the deliberate two-step model that keeps unrelated edits out of history.
3. You are about to stage configMap.yaml, but you are unsure whether a real database password is still present in the edited lines. What should you inspect before staging, and what decision should follow?
Run git diff before staging so you can inspect the exact unstaged line changes. If the diff contains a real password, do not stage or commit it; remove the secret, replace it with a safe placeholder or external reference, and verify the diff again. git log would not help because the risky content is not committed yet. The safest decision is to make the patch clean before it enters the staging area.
4. You cloned a repository and Git refuses to commit because no author identity is configured. Later, git push asks for remote credentials. Why are these different?
user.name and user.email supply commit attribution; they do not authenticate a push. Remote credentials authenticate to the host, and the host separately decides whether that identity is authorized to push. For example, GitHub repository roles distinguish read access from permission to push. A successful local commit does not guarantee the remote will accept a push.
5. You created aws-credentials.json for a local test and never want it committed. What should you do before staging other work, and what limitation must you remember?
Add aws-credentials.json to .gitignore before broad staging, then use git status to check it is no longer an untracked candidate. Ignore rules do not untrack a committed file or erase earlier history. If a real credential was pushed, revoke or rotate it; for local-only history, stop before pushing and follow the credential response steps.
6. A learner deletes the hidden .git directory to "reset" a broken project, then runs git status. What happens, and why is this not a safe recovery method?
Git reports that the directory is not a repository unless a parent directory is itself a Git repository, in which case Git may use that parent instead. The deleted .git contained local history and metadata; deleting it is not a safe reset. Start recovery with observation commands and a clear goal, such as unstaging a file or reverting a commit.
7. You and a colleague committed different edits to the same replicas line. Their commit reached the remote first, and your push is rejected. After fetching and inspecting the divergent histories, you choose git pull --no-rebase origin main. What might happen, and how would you resolve it?
Git may stop with a merge conflict; it cannot choose the operationally correct replica count. Check git status for unmerged paths, read the conflict markers, agree on the intended value, remove the markers, and stage the resolved file with git add. Inspect the staged resolution and complete the merge with git commit, then verify the result before retrying the push. If you chose rebase instead, follow its status instructions and use git rebase --continue after staging. If an editor opens during either operation, read and save the message and close it using that editor’s instructions. A conflict is not guaranteed for every pair of edits.
Hands-On Exercise
Section titled “Hands-On Exercise”In this exercise, you will create a local repository from scratch, simulate a standard engineering workflow by making multiple logical commits, and observe the resulting history. The files are small Kubernetes-style examples, not cluster tests. Before Task 1, return to a practice directory under your control. If still in the theory child, exit returns to the shell and directory where you started it; alternatively, cd .. moves within that child to the practice parent. Read git status after each step and do not use real credentials.
Task 1: Initialization
Section titled “Task 1: Initialization”Create a new directory named dojo-k8s-project, navigate into it, and initialize an empty Git repository so you can observe the first status report from a clean practice workspace.
Start another disposable child Bash from that practice directory with bash --noprofile --norc alone, then wait for its prompt. Paste the full grouped solution only inside that child and stay there for Tasks 2–8. When finished, exit returns to its parent shell; if you started it inside the theory child, a second exit returns to the original shell. A repeat run needs an unused name. If setup fails, the child exits: STOP and do not paste later tasks into its parent.
- Directory created and navigated into.
- Git repository initialized.
Solution: Task 1
{set -etrap 'printf "%s\n" "STOP: setup failed; do not continue in the parent shell."' EXITunset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_OBJECT_DIRECTORY GIT_COMMON_DIRmkdir dojo-k8s-projectcd ./dojo-k8s-projectpractice_dir=$(pwd -P)git init --initial-branch=maintest "$(git rev-parse --show-toplevel)" = "$practice_dir"test "$(git rev-parse --absolute-git-dir)" = "$practice_dir/.git"git config --local user.name "KubeDojo Learner"git config --local user.email "learner@example.invalid"git statusprintf 'Practice repository ready: %s\n' "$practice_dir"trap - EXITset +e}Task 2: The Initial Commit
Section titled “Task 2: The Initial Commit”Create a README.md file with the text ”# KubeDojo Project”. Stage the file and commit it with the message “docs: add initial readme”. This task checks that you can move a new file through the working directory, staging area, and repository history without skipping the state checks.
- File created with correct content.
- File added to staging area.
- Commit successfully created.
Solution: Task 2
echo "# KubeDojo Project" > README.mdgit statusgit add README.mdgit statusgit commit -m "docs: add initial readme"Task 3: Simulating Infrastructure Development
Section titled “Task 3: Simulating Infrastructure Development”Create a file named deployment.yaml and add the following dummy content so the repository has an infrastructure-style file to track. This is an incomplete Git practice fragment, not a deployable Deployment; do not apply it to a cluster.
apiVersion: apps/v1kind: Deploymentmetadata: name: webStage and commit this file with the message “feat: add web deployment skeleton” after confirming that Git reports the file as untracked.
- File created.
- Commit successfully created with correct message.
Solution: Task 3
cat << 'EOF' > deployment.yamlapiVersion: apps/v1kind: Deploymentmetadata: name: webEOF
git statusgit add deployment.yamlgit commit -m "feat: add web deployment skeleton"Task 4: Modifying Existing Files
Section titled “Task 4: Modifying Existing Files”Open deployment.yaml and add replicas: 3 under a spec: block, then inspect the resulting line change before you stage it:
apiVersion: apps/v1kind: Deploymentmetadata: name: webspec: replicas: 3Use a command to view the exact differences before staging. Then, stage and commit the change with the message “fix: set deployment replicas to 3”.
- File modified.
- Diff viewed successfully.
- Change staged and committed.
Solution: Task 4
# Modify the file using your preferred editor (nano, vim, or cat override)cat << 'EOF' > deployment.yamlapiVersion: apps/v1kind: Deploymentmetadata: name: webspec: replicas: 3EOF
# View the diffgit diff
# Stage and commitgit add deployment.yamlgit commit -m "fix: set deployment replicas to 3"Task 5: Reviewing the Timeline
Section titled “Task 5: Reviewing the Timeline”Run a command to view your complete commit history in a compact, single-line format. Verify that all three of your commits are present with the most recent first (the default for git log --oneline). If a commit is missing, use git status to determine whether the change is still unstaged, staged, or never created.
- History command executed.
- Three distinct commits visible in the output.
Solution: Task 5
git log --onelineOutput should look similar to the following example; the hashes are illustrative:
3b2a1c4 fix: set deployment replicas to 39f8e7d6 feat: add web deployment skeleton1a2b3c4 docs: add initial readmeTask 6: Bonus Challenge — Advanced Ignore Rules
Section titled “Task 6: Bonus Challenge — Advanced Ignore Rules”You are working on a new application that generates numerous log files ending in .log across various directories. You want Git to ignore them while allowing the root file audit-trail.log to be deliberately tracked as an exception. Create and test the ignore rules; an exception permits staging that file but does not add or commit it automatically.
-
.gitignorefile created with appropriate wildcard and exclusion rules. - Dummy files created to test the rules.
-
git statusshows.gitignoreand the rootaudit-trail.logas untracked; the other logs, includinglogs/audit-trail.log, are ignored.
Solution: Task 6
# Create the .gitignore filecat << 'EOF' > .gitignore*.log!/audit-trail.logEOF
# Create dummy filestouch app.logtouch database.logtouch audit-trail.logmkdir -p logstouch logs/audit-trail.log
# Check statusgit statusGit will show .gitignore and the root audit-trail.log as untracked files. The other .log files, including the nested namesake, are ignored.
Task 7: Git-State Diagnostic
Section titled “Task 7: Git-State Diagnostic”Attempt this diagnostic before opening the progressive hints or full solution. Two realistic scenarios test whether you can interpret Git state and choose the correct operational action: git add, git commit, ignore configuration, git fetch/git pull, or do nothing. Record which hints you needed, then repeat the diagnosis without them.
Challenge 1: The Planted Workspace Trap. Run the following setup snippet inside your dojo-k8s-project directory to plant staged modifications, unstaged modifications, and untracked files. The incident-token.env file is an empty dummy; never put a real credential in this exercise. The appended text is incomplete scratch content, not a deployable manifest.
# Plant messy workspace stateecho "port: 8080" >> deployment.yamlgit add deployment.yamlecho " # verify container port" >> deployment.yamltouch temp-notes.txttouch incident-token.envBefore running any fix or commit, inspect the repository state and answer these four questions in your notes:
- Why does
deployment.yamlappear twice in the output ofgit status? - How do you view the change that is staged for commit versus the change that is only in your working directory?
- Which files must be kept out of version control, and what action ensures they are ignored?
- What is the precise command sequence to safely ignore the credential and scratch files, unstage the incomplete YAML edit, and return the working tree to clean?
Try the questions first. If you are stuck, open the hints one at a time before reading the solution.
Hint 1: think about copies
The working file and the index can hold different versions. Which copy would the next commit use, and which copy can you still edit?
Hint 2: choose what to inspect
Look at the workspace status and both comparisons: index against the last commit, and working file against the index. Consider which untracked paths should stay out of history.
Hint 3: choose commands
Use git status, git diff --staged, and git diff to inspect before changing anything. To remove this already-tracked file’s staged change from the next commit, consider git restore --staged deployment.yaml; inspect the result before discarding or committing any work.
Challenge 2: The Divergent Timelines Diagnostic. This paper diagnostic is your practice comparing local and remote timelines. A colleague reports that git push origin main was rejected. After a fetch, they share an illustrative local log and origin/main, their local record of the server branch at that moment:
Local log:f1a2b3c (HEAD -> main) feat: add redis cache deployment3b2a1c4 fix: set deployment replicas to 39f8e7d6 feat: add web deployment skeleton
Remote tracking log (origin/main):d4e5f6a (origin/main) chore: update prometheus scrape annotations3b2a1c4 fix: set deployment replicas to 39f8e7d6 feat: add web deployment skeletonWithout running commands, diagnose the repository state:
- Why was
git pushrejected, and what does the divergence betweenHEADandorigin/mainindicate? - What should the engineer do next:
git commit,git push --force,git fetchfollowed by inspection, orgit init? - What risk could
git push --forceintroduce for the shared branch?
Try the diagnosis before opening these hints. Record which one helped.
Hint 1: compare histories
Find the shared commit, then identify what each branch has added since it.
Hint 2: inspect before integrating
The fetched ref is a local record that can become stale. Compare both directions before choosing how to combine the work.
Hint 3: choose commands
Consider git fetch origin, then git log HEAD..origin/main and git log origin/main..HEAD. Discuss merge or rebase before retrying; inspect the error if the push still fails.
- Planted workspace state diagnosed using
git status,git diff, andgit diff --staged. - Appropriate action chosen for each file (stage, unstage, or ignore).
- Divergent remote timeline diagnosed with the correct synchronization action identified.
Solution: Task 7 Diagnostic Walkthrough
For Challenge 1 (The Planted Workspace):
deployment.yamlappears twice ingit statusbecause it has two distinct states simultaneously: one line addition (port: 8080) was staged withgit add, and a subsequent comment addition (# verify container port) was made in the working directory after staging. The staging area holds a snapshot of how the file looked at the momentgit addran.- Run
git diff --stagedto inspect the changes staged for the next commit (port: 8080), and run plaingit diffto inspect the unstaged working tree modification (# verify container port). - The empty
incident-token.envis a dummy standing in for a credential file and must not be committed.temp-notes.txtis scratch documentation. Both should be added to.gitignore(or deleted from disk). - To clean up safely:
- Add narrow ignore patterns: append
incident-token.envandtemp-notes.txtto.gitignore. - Unstage the incomplete YAML change: run
git restore --staged deployment.yaml. For this already-tracked file,git reset HEAD deployment.yamlis an alternative;git rm --cached deployment.yamlwould remove the file from tracking entirely, which is not what you want here. - Discard the unwanted scratch edits from the working copy: run
git restore deployment.yaml(or remove the extra lines innano). Restore discards the unstaged edits in this file; only run it after confirming they are not needed, because Git cannot recover edits it never saved. - Leave the empty dummy files ignored, or remove them if you no longer need them.
- Review
.gitignoreand stage it withgit add .gitignore. If you completed Task 6, also review and stage the empty dummyaudit-trail.log; otherwise there is no audit file to stage. Commit these intended files withgit commit -m "chore: record practice ignore rules", then rungit statusto confirm a clean working tree. Ignoring scratch files alone does not commit the ignore rules or the audit exception.
- Add narrow ignore patterns: append
For Challenge 2 (The Divergent Timelines):
- The shown local and fetched tips diverge:
d4e5f6ais not in the local branch. That is consistent with a non-fast-forward rejection, although the server may have moved since the fetch. - Run
git fetch originto refresh the local record, then inspectgit log HEAD..origin/mainfor remote-only commits,git log origin/main..HEADfor local-only commits, andgit diff HEAD...origin/mainfor the fetched side’s changes since the merge base. Agree on merge or rebase, verify the result, and only then retry the push. - A force push can move the shared branch away from the teammate’s commit, making it unreachable from that branch. Other clones may retain it, but recovery depends on available copies and cleanup. Avoid forcing a shared branch without coordination.
--force-with-leasecompares the expected remote value, not whether the teammate’s commit is included locally. Both manual and background fetches can update the tracking ref used as that expectation. Here, after fetching, a lease could succeed while dropping the teammate’s commit from the branch. It does not replace integration. See the Git 2.56 push documentation.
Transfer check: A teammate stages an edit to config.yaml, then makes another edit without staging it. Which command displays each change, and what would the next commit include?
Check your answer
git diff --staged compares the index with HEAD; git diff compares the working file with the index. The commit includes the staged version, not the later unstaged edit. If both edits are intended, stage the file again and inspect the staged diff before committing.
Task 8: Design Your Own Two-Commit Workflow
Section titled “Task 8: Design Your Own Two-Commit Workflow”Continue in the same disposable repository after Task 7 is clean. Choose a new replica count for the practice deployment.yaml fragment and explain your choice in a new line of README.md. The fragment is incomplete and must not be applied to a cluster. Recreate temp-notes.txt if you removed it. Run git ls-files -- temp-notes.txt first: if it prints the path or the command fails, stop and investigate before changing ignore rules. See Git 2.56: ls-files. For an untracked path, run git check-ignore temp-notes.txt, then immediately run echo "$?" as the next command to display its exit status. Status 0 with the printed path means it is ignored; tracked files are not reported by default. If the check exits with status 1 and prints nothing, add a narrow ignore pattern, review and commit .gitignore first; stop on any other exit status (for example 128). Use that ignored file for a scratch note; do not put credentials in it. See Git 2.56: check-ignore.
Before editing, write down the two commit purposes and predict which files will be staged, unstaged, and ignored. Make both edits, then stage only the replica change. Inspect the index against HEAD and the working tree against the index before the first commit: explain why the README is still outside that commit. Commit the configuration change, then review and commit the README change separately. Check that both patches contain only the intended file, the scratch note is ignored and untracked, and normal git status is clean. Record which hints you used and what you would change in your workflow next time.
Hint 1: choose the boundaries
Which change describes the configuration, and which explains your decision? Decide what each snapshot should contain before you stage anything.
Hint 2: inspect the two copies
After staging one file, compare the index to the last commit and the working files to the index. Check the scratch path against the ignore rules before committing.
Hint 3: choose commands
Use git ls-files -- temp-notes.txt first; if it prints the path or fails, stop and investigate before changing ignore rules. For an untracked path, run git check-ignore temp-notes.txt and immediately run echo "$?" to distinguish an ignored path (0), not ignored (1), and any other exit status (for example 128). See the check-ignore reference. Use git status, git diff, git add deployment.yaml, and git diff --staged for the two-copy check. After the first commit, inspect and stage README.md, then compare the two commits with git log -p -2.
Example reflection after your attempt
One possible approach is to choose two replicas for a smaller practice configuration and write that reason in the README. The first staged patch changes only the replica line while the README remains unstaged; the second commit contains only the explanation. The ignored scratch note stays on disk, and the final status is clean under normal untracked-file reporting. Another count and a different reason are valid if the two patches and explanation match your choice.
Success Criteria
Section titled “Success Criteria”- You can explain the difference between the working directory, staging area, and repository history using your own practice files.
- You created at least three focused commits with meaningful messages.
- You inspected a diff before staging a Kubernetes-style YAML change.
- You used
git log --onelineto verify the resulting history. - Optional Task 6: you created and tested a
.gitignorerule that ignores a broad pattern while allowing one exception. - You diagnosed complex repository states and divergent timelines using status, diff, and log, recording any hints used.
- You designed and checked two focused commits for your own replica choice and explanation, with the scratch note ignored.
Sources
Section titled “Sources”- Git 2.56: init, config, add, commit, diff, and gitignore
- Git 2.56: fetch, pull, and push and leases
- Git 2.56: merge and rebase
- Git 2.56: clone, restore, reset, and remote
- Git 2.56: check-ignore, reflog, rm, and log
- Git 2.56: status, ls-files, and index format
Further reading (live documentation may change):
- Git documentation and the Git book: Getting Started, A Short History of Git, and Git Basics
- GitHub: removing sensitive data
- GitHub: authentication
- GitHub: repository roles and push permissions
- Kubernetes v1.35: labels and Deployments
- GitHub Git Guide
- GitHub Git Guide: git pull
- GitHub gitignore templates
Next Module
Section titled “Next Module”Module 0.7: What is Networking? — Now that you can track files, it is time to understand how computers talk to each other across networks.