7  Git and GitHub for Solo Developers

In March you write the cleaning script for a readmissions analysis, and it excludes patients with implausible blood pressures. In November a reviewer asks why 212 patients were excluded when the protocol implies fewer. The person who must answer is you, eight months and three projects later, with no memory of the decision. Without a history, the answer is a reconstruction from memory and from files named clean_final2.R. With Git it is one command, git log -p R/clean.R. It shows when the exclusion rule changed and what it changed from. If the March analyst wrote a good commit message, it also shows why. That is, over the life of a project you work with your own earlier self, at a distance in time, and Git supports that work.

Those who cannot remember the past are condemned to repeat it.

George Santayana, The Life of Reason (1905)

Diagram of the analysis pipeline: six stages in order (Plan, Acquire, Wrangle, Analyze, Report, Share) above two bands that run under every stage (Version control and Environment). Highlighted for this chapter: Version control.
Figure 7.1: Where this chapter sits: Git is the Version control band, which runs under every stage of the analysis.
NoteIn this chapter

Reading time. About 30 minutes.

You’ll need. A terminal, and Chapter 6 for Git installed and configured with your name and email. Chapter 5 is an optional introduction to the command line. Every command in this chapter runs in a shell, not in R, so the examples are display-only; the exercises build a throwaway practice repository, and each solution gives the output to expect.

You’ll be able to.

  • Make commits that each record one logical change with a message that says why, and read the history back with git log.
  • Experiment on a branch, merge it, and resolve a merge conflict.
  • Push to a private GitHub repository over SSH or with a token, and tag the commit you submit.
  • Recover from the common mistakes, choosing the command that destroys nothing first.

Outline.

If these answers come quickly, skip to the next chapter. The answers are in Section 7.12.

  1. Why should a solo biostatistician use Git for a project that no one else will ever see?
  2. What is the difference between a commit, a branch, and a tag?
  3. Name one common scenario in which git stash saves you from data loss.

7.1 Why one analyst needs a history

Nearly every argument for version control is an argument about collaboration: merging other people’s work, reviewing their changes, avoiding the overwrite of a file two people edited at once. None of that applies to an analyst working alone. For that reason, solo Git is harder to justify than it looks, and many statisticians postpone learning it until a project forces the issue.

The case for solo use rests on the March and November analysts. Everything Git offers a team it offers to that pair, and each of November’s questions has a Git answer (Table 7.1).

Table 7.1: What Git gives one analyst.
November’s question What answers it Command
When did this number change, and why? The commit history and its messages git log -p R/clean.R
Exactly what did we submit? A tag on the submitted commit git switch --detach v1.0-submission
Can I try a risky change without endangering the analysis of record? A branch git switch -c sensitivity
What if the laptop dies? A copy on a remote server git push
The project now has a second analyst Nothing new: the history and the remote already exist Chapter 8

The cost is a few hours of learning and a few seconds per commit. The benefit recurs on every project for the rest of your career. In addition, many ‘solo’ projects become team projects. At that point, a repository that already exists is the difference between sharing code in an afternoon and scrambling for a week.

Question. You keep dated copies of the project folder (analysis_2026-03-14/, analysis_2026-04-02/). What does that give the November analyst, and what does it not?

Answer. It records when, coarsely, and lets you recover a whole folder. It does not record what changed (you must diff folders by hand), why it changed (there is no message), or which copy was submitted (unless you remember the date). It also makes experiments expensive, since each one is another full copy, and nothing stops you from editing an old copy by mistake. By contrast, a commit records a line-level change with a reason. A tag names the submitted state, and a branch makes an experiment free.

7.2 The everyday cycle

On most days, Git is five commands: look, compare, stage, commit, repeat (display-only, as is every command in this chapter).

# once per project
cd ~/research/my-project
git init -b main
git add .
git commit -m "Initial project structure"

# day to day
git status
git diff
git add R/clean.R
git commit -m "Exclude SBP above 280 mmHg, per SAP section 6.2"
git log --oneline -10

git diff shows changes you have not yet staged. git diff --staged shows what the next commit will contain. The distinction is between ‘I have edited this’ and ‘I have marked this for the next commit’. The second command is the one to read before every commit.

WarningPitfall

git add . stages whatever is in the directory. On an analysis project that is routinely more than you meant: a rendered PDF, a cache directory, a data extract you are not licensed to redistribute, an .Renviron holding a database password. Git does not distinguish among them. Read git status before staging, list derived and secret files in .gitignore, and consider a secret scanner such as gitleaks as a pre-commit hook.1 A credential that reaches a pushed commit must be treated as compromised and rotated, even after the file is deleted. The old commit still contains it.

1 One way to automate part of this is the in-house zzgit zsh plugin (Appendix C), which wraps staging and committing with a prompt for a Conventional Commits subject line and a confirmation before pushing to a protected branch. Content scanning requires gitleaks to be installed separately. Without it, zzgit falls back to a filename check only, and it will commit a secret in a file like .Renviron without warning. The protected-branch confirmation guards a push, not a commit. Install gitleaks as a pre-commit hook, with or without zzgit, for the content scan itself. zzgit is optional.

7.2.1 Commits as units of reasoning

Git’s commands can be memorized in a week. However, a repository that answers questions differs from one that only stores files in two habits, and the commands do not enforce either of them.

Each commit is one logical change. ‘Refactor data cleaning to use vectorized assignment’ is a commit; ‘Tuesday’s work’ is not. Atomic commits make git bisect feasible. This is the binary search for the commit that introduced a bug (Chapter 8). Large commits make it useless.

The message says why. The diff already shows what changed. Only the message can say why (Table 7.2, in which SAP is the statistical analysis plan of Chapter 26).

Table 7.2: Commit messages for the November analyst.
A message that says what A message that says why
update SEs Switch to HC1 sandwich standard errors: residual plots show heteroscedasticity
fix filter Exclude SBP above 280 mmHg, per SAP section 6.2
changes Drop site E visits before 2024-03: export bug confirmed by data manager
Tuesday’s work (Three commits, one per change)

A useful test is to write the message first. If it needs the word ‘and’, or a list of unrelated items, the commit is doing too much.

git log has many options, but the useful subset is short.

git log --oneline -10
git log --grep "bootstrap"
git log -p R/clean.R
git log --since="2 weeks ago"

These show, in order, the last ten commits one line each, the commits whose message mentions ‘bootstrap’, every change ever made to one file with its diff, and recent activity.

7.2.2 Exercises

  1. Build the practice repository the rest of this chapter’s exercises use. In an empty directory (for example ~/git-practice), run the commands below, then run git status and git log --oneline. What do they print?
git init -b main
printf '# HF-HOME practice\n' > README.md
git add README.md
git commit -m 'Add README'
mkdir R
printf 'visits <- read.csv("visits.csv")\nthreshold <- 250\n' > R/clean.R
git add R/clean.R
git commit -m 'Read visits as exported'
printf 'stopifnot(!anyDuplicated(visits$visit_id))\n' >> R/clean.R
git commit -am 'Assert one row per visit'

git status prints On branch main and nothing to commit, working tree clean. git log --oneline prints three lines, newest first. Your seven-character hashes will differ, because a hash depends on the author, time, and content:

fb2dbac Assert one row per visit
37c6e4f Read visits as exported
94a17b3 Add README

The last commit used git commit -am, which stages every change to a file Git already tracks and commits it in one step. It does not pick up new files, which is why the first two commits needed git add. If git log shows fewer commits, run git status. A commit that failed for want of a configured name and email (Chapter 6) leaves the change staged.

Question. In one morning you cleaned the data, fixed a typo in the README, fitted three candidate models, and deleted an old script. How many commits is that, and what is the test?

Answer. Several, and the test is whether you could revert one part without losing the others. Cleaning the data, fixing the README, and deleting the script are three unrelated intentions. If they are bundled together and you discover next week that the cleaning rule was wrong, reverting it means reverting the README fix too. The three model fits depend on intent. If they are alternatives you are choosing between, commit each, so that you can point at the one you kept. If they are one specification search you always meant to run together, they are one commit. Solo work needs this discipline more than it seems to, because you are the only reviewer you will ever get.

7.3 Branches and merges

A branch is a movable pointer to a commit. Creating a branch makes a new pointer, and the branch moves forward as you commit on it. Figure 7.2 shows the shape a solo analyst’s history tends to take. A main line carries the trustworthy analysis. Short-lived branches hold experiments, which are merged back if they work out and abandoned if they do not.

gitGraph
  commit id: "init compendium"
  commit id: "clean data"
  branch sensitivity-analysis
  checkout sensitivity-analysis
  commit id: "MNAR sensitivity"
  commit id: "tipping point"
  checkout main
  commit id: "primary model"
  merge sensitivity-analysis
  commit id: "manuscript" tag: "submitted-v1"
Figure 7.2: A solo analyst’s branch history. The main line carries the analysis of record and is tagged at submission; a sensitivity-analysis branch explores an alternative and is merged only once it is trusted.

The commands that produce such a history:

git switch -c sensitivity-analysis
git add R/sensitivity.R
git commit -m "Add sensitivity analysis under MNAR"
git switch main
git merge sensitivity-analysis
git branch -d sensitivity-analysis

git switch -c creates a branch and moves to it, and git switch main moves back. git merge brings the branch’s commits into the current branch. git branch -d deletes a branch whose work has been merged.2 MNAR (missing not at random) is the kind of sensitivity analysis a solo analyst most often wants to try without committing to it (Chapter 21).

2 git switch and git restore arrived in Git 2.23 (2019) to split the many jobs of git checkout, which still works and appears in older guides.

For solo work, branches suit three kinds of work. The first is an experiment you might throw away, such as a risky refactor. The second is a side investigation, such as a sensitivity analysis you may or may not report. The third is a separable piece of a longer project. The discipline is to keep main working at all times. If a branch is half-done, leave it on its branch.

git rebase is an alternative to merge that produces a linear history. For solo work the difference rarely matters, so pick one and use it consistently. merge is simpler to reason about.

7.3.1 When a merge conflicts

If the branch and main both changed the same lines, Git cannot choose and stops with a merge conflict. It writes both versions into the file between markers:

visits <- read.csv("visits.csv")
<<<<<<< HEAD
threshold <- 280
=======
threshold <- 300
>>>>>>> sbp-300
stopifnot(!anyDuplicated(visits$visit_id))

The lines between <<<<<<< HEAD and ======= are the current branch’s version. Those between ======= and >>>>>>> sbp-300 are the incoming branch’s. To resolve the conflict, edit the file to the content you intend, which may be either side, both, or neither, and delete all three marker lines. Then run git add R/clean.R and git commit --no-edit, which records the merge with Git’s default message. For analysis code, both sides usually represent deliberate decisions. Here one is the SAP’s threshold and the other a sensitivity analysis. The right resolution keeps the SAP value in the primary script and moves the alternative to its own script.

TipVerification

Before committing a resolution, confirm that no markers remain anywhere in the tracked files, then rerun the analysis:

git grep -n -e '<<<<<<<' -e '>>>>>>>'

No output means no markers. A marker left in an R script stops the script with a parse error. A marker left in a CSV or a Markdown file, however, is read as data or text without complaint.

7.3.2 Exercises

  1. In the practice repository, plant and resolve a conflict. Create a branch sbp-300 and set threshold <- 300 in R/clean.R; commit. Switch to main and set threshold <- 280; commit. Merge sbp-300, resolve the conflict in favor of 280, and commit. What does git log --oneline --graph print?

One way to make each edit without an editor is to rewrite the file whole, as here for the branch (use 280 on main):

printf '%s\n' 'visits <- read.csv("visits.csv")' \
  'threshold <- 300' \
  'stopifnot(!anyDuplicated(visits$visit_id))' > R/clean.R

The merge prints CONFLICT (content): Merge conflict in R/clean.R, and git status --short marks the file UU. After the resolution and git commit --no-edit, the graph shows the two lines of work meeting at the merge commit (your hashes and the order of the two middle commits may differ):

*   11d6d7e Merge branch 'sbp-300'
|\
| * 2853126 Raise SBP threshold to 300 for sensitivity
* | 93d5df5 Set SBP threshold to 280 per SAP
|/
* fb2dbac Assert one row per visit
* 37c6e4f Read visits as exported
* 94a17b3 Add README

cat R/clean.R shows threshold <- 280 and no marker lines. Delete the merged branch with git branch -d sbp-300.

Question. A merge completes with no conflict. Does that mean the merged analysis is correct?

Answer. No. Git detects only overlapping edits to the same lines. Suppose the branch renamed a variable in one file and main added a use of the old name in another. The merge is clean, and the script fails or, worse, finds a stale object and runs. Rerun the analysis after every merge. Chapter 8 returns to these semantic conflicts, which become common once two people share a repository.

7.4 Remotes and authentication

A remote is a copy of the repository hosted elsewhere. GitHub is the dominant choice. GitLab is similar, and Gitea is a self-hosted alternative. Even for solo work, a remote is your off-site backup. A laptop fire ends a project that was never pushed. For one that was pushed, it is only a setback.

gh repo create my-analysis --private --source=. --remote=origin
git push -u origin main

git push
git pull

The first line creates a private repository with the GitHub command-line tool gh and registers it as the remote origin. The -u origin main on the first push sets the upstream, so that later git push and git pull need no arguments. Make repositories public deliberately, never by accident. A private repository costs nothing.

GitHub stopped accepting account passwords for Git operations in 2021, so you authenticate in one of two ways.

Table 7.3: Authenticating to GitHub.
Method Setup Use when
Personal access token (PAT) Create a fine-grained token in your GitHub settings, limited to the repositories it needs, with an expiration date; or let gh auth login create and store one You want the fastest start, or you work over HTTPS (HyperText Transfer Protocol Secure)
SSH (Secure Shell) key ssh-keygen -t ed25519 -C "you@example.com", then add the public key with gh ssh-key add ~/.ssh/id_ed25519.pub or in your GitHub settings You push often from one machine; clone with git@github.com:user/repo.git URLs

Either works, and gh auth login handles the common case for both. GitHub’s settings menus move from time to time. If a path in its documentation has changed, search for ‘personal access token’ or ‘SSH keys’.

7.4.1 Exercises

  1. Create a private GitHub repository for the practice repository and push main to it. How do you confirm, from the shell, that the remote has your latest commit?

From inside the repository, gh repo create git-practice --private --source=. --remote=origin followed by git push -u origin main. Then git status should include Your branch is up to date with 'origin/main', and the hash git ls-remote origin main prints should equal the one git rev-parse main prints. git status compares against the last state Git fetched. git ls-remote asks the server now, which is the stronger check. Delete the practice repository on GitHub when you finish the chapter (gh repo delete git-practice, which needs the delete_repo scope).

Question. You pushed a commit that added .Renviron with a database password to a private repository, then deleted the file in the next commit. Is the password safe?

Answer. No. The earlier commit still contains the file. Anyone with access to the repository, now or after it is made public or shared with a collaborator, can read it with git show <hash>:.Renviron. Rotate the password first, since that is the step that protects the database. Removing the file from history requires rewriting it and force-pushing, which does not reach copies already cloned.

7.5 Tags and detached HEAD

A tag is an immovable, named pointer to a commit. Tag the moments you may need to return to exactly: submission to a journal, each round of revision (v1.1-revision-1), the published version, and internal milestones such as results sent to the principal investigator (PI).

git tag -a v1.0 -m "Submitted to Journal of Biostatistics 2026-04"
git push origin v1.0
git tag
git switch --detach v1.0
git switch main

The -a makes an annotated tag, which records who tagged, when, and a message. Prefer it to a lightweight tag. Tags are not pushed by git push alone, so push each one by name. Once a tag is pushed, treat it as permanent.

7.5.1 Detached HEAD

git switch --detach v1.0 (or the older git checkout v1.0) puts the repository in a detached HEAD state. That is, you are on a commit, not on a branch. Looking around, rerunning, and rendering are all safe. A commit made there belongs to no branch, and it drops out of view when you switch away. To build on a tagged version, create a branch from it first: git switch -c revision-1 v1.0.

Suppose a reviewer asks, six months later, for a rerun with the original exclusion criterion. Switch to the submission tag, rerun, compare with main, and switch back. The tag is the record of which version was reported.

7.5.2 Exercises

  1. Tag the current commit of the practice repository as v1.0-submission, with a message. What does git log --oneline --decorate -1 print? Then switch to the tag with --detach: what is the first line of git status?

After git tag -a v1.0-submission -m 'Submitted to journal', the log line carries both pointers:

11d6d7e (HEAD -> main, tag: v1.0-submission) Merge branch 'sbp-300'

After git switch --detach v1.0-submission, git status begins HEAD detached at v1.0-submission. Return with git switch main. If you pushed the repository in Exercise 3, push the tag with git push origin v1.0-submission.

Question. You have committed and pushed your finished analysis. Why also tag the commit?

Answer. A commit hash such as a3f9c8d is unmemorable and looks like every other hash. In two years you will not know which one you submitted. The tag v1.0-submission is human-readable, records when and why it was made, and appears in the repository’s list of tags on GitHub. A GitHub Release is a separate object built on a tag, with notes and attached files, and exists only if you create one (gh release create v1.0-submission).

7.6 Recovery

Most Git mistakes can be undone, and the first move is almost always one that destroys nothing. Table 7.4 lists the common ones in the form you will meet them.

Table 7.4: The ‘Oh no, I…’ table. Run git status before and after each fix.
Oh no, I… Run Destroys anything?
edited a file and want the committed version back git restore R/clean.R Yes: your uncommitted edits to that file
staged a file I did not mean to git restore --staged R/clean.R No
wrote a bad message on the last commit (not yet pushed) git commit --amend -m "Better message" No
committed too early and want the changes back (not yet pushed) git reset --soft HEAD~1 No: the changes stay staged
committed to main instead of a new branch (not yet pushed) git branch topic, then git reset --hard HEAD~1, then git switch topic No, if the working tree was clean first
pushed a commit that was wrong git revert <hash> No: a new commit undoes it
ran git reset --hard and lost commits git reflog, then git reset --hard HEAD@{1} No, if the reflog shows the commit
committed while in detached HEAD git switch -c rescue before switching away; afterward, find it in git reflog No
need to switch branches with unfinished work git commit on the branch, or git stash No
pushed a secret Rotate the credential first; then see the Check in Section 7.4 The secret is already exposed

7.6.1 The commands behind the table

git reset moves the current branch to another commit. Its three modes differ only in what happens to the changes the move skips over.

git reset --soft HEAD~1
git reset HEAD~1
git reset --hard HEAD~1

The first undoes the last commit and keeps its changes staged. The second keeps them unstaged, and the third discards them. HEAD~1 means ‘one commit before the current one’.

git reflog lists every move of HEAD in your local repository, including the ones reset hides from git log. Commits that no branch reaches remain listed there for 30 days by default (the gc.reflogExpireUnreachable setting), and entries for commits still on a branch for 90 days. It is the recovery mechanism of last resort. If you deleted a commit in a panic, the reflog probably still has it.

git stash sets uncommitted work aside so that you can switch branches, and git stash pop brings it back. Prefer a commit for work that matters. A popped or dropped stash leaves the reflog. It survives only as an unreachable object, which git fsck --no-reflogs --unreachable lists until garbage collection prunes it, typically after two weeks.

WarningPitfall

git reset --hard deletes uncommitted work, and nothing brings it back. The reflog records commits, not edits you never committed. Before any command marked ‘Yes’ in Table 7.4, run git status. If anything you want is listed, commit it first (on a scratch branch if need be).

ImportantLLM prompt

Recovery is where a model’s first suggestion is most often destructive. Give it the evidence and forbid the shortcut.

Context. Below are the output of git status, git log --oneline --graph -15, and git reflog -15 for my analysis repository. What went wrong: [I ran git reset --hard and the commit ‘Fit primary model’ is gone from git log].

Constraints. Use the reflog before anything else. Propose no reset --hard, clean -f, push --force, or restore . unless you first give a command that preserves the current state (a branch or a commit). Explain what each command does before I run it.

Criteria. After your commands, git log --oneline shows the lost commit, git status shows nothing I had before is lost, and you state which reflog entry you used.

Failure mode. The model reaches for git reset --hard or git push --force first. On a tree with uncommitted work, that destroys exactly what the reflog cannot restore. A coding agent with a shell adds a second risk, since it may run the command before you read it. Before any agent session that can edit the repository, make a commit or start a branch (git switch -c agent/<task>). Then git diff main shows everything the agent did, and git switch main abandons it. Check. Run the three criteria commands yourself. Status, log, and reflog output hold file names and messages, not data, so they may go to any approved tool. Read the messages for identifiers first (Section 12.3).

7.6.2 Exercises

  1. In the practice repository, commit a new line (printf 'n_visits <- nrow(visits)\n' >> R/clean.R, then git commit -am 'Count visits'), destroy the commit with git reset --hard HEAD~1, and recover it. Which reflog entry do you use, and how do you confirm the recovery?

git reflog -2 shows the reset on top and the lost commit one entry below it:

11d6d7e HEAD@{0}: reset: moving to HEAD~1
aa1302f HEAD@{1}: commit: Count visits

git reset --hard 'HEAD@{1}' restores it (the quotes stop some shells from expanding the braces). git log --oneline -1 then prints aa1302f Count visits (your hash differs), and tail -n 1 R/clean.R prints the restored line. --hard is safe here only because git status was clean before the reset.

Question. Which of these can the reflog recover: (a) a commit removed by git reset --hard; (b) edits you made and never committed, then discarded with git restore; (c) a commit on a branch you deleted with git branch -D last week?

Answer. (a) and (c). Both were commits, and the reflog records every commit HEAD has visited for at least 30 days. (b) cannot be recovered by Git at all, because Git never saw the edits. Only an editor’s undo history or a backup can help. This asymmetry is the practical argument for committing early and often.

7.7 Worked example: a solo project lifecycle

The lifecycle below is display-only. It shows when each command runs over the life of one project.

# day 1: start the project
mkdir ~/research/readmissions && cd ~/research/readmissions
git init -b main
echo "# Readmissions analysis" > README.md
printf '%s\n' '*.html' '*.pdf' '.Rproj.user/' '.Rhistory' \
  '.RData' '.Renviron' > .gitignore
git add . && git commit -m "Initial structure"
gh repo create readmissions --private --source=. --remote=origin
git push -u origin main

# week 2: data exploration
git add R/01_explore.R
git commit -m "Initial EDA, summarizing 30-day rates"

# week 4: try a sensitivity analysis on a branch
git switch -c sensitivity-mnar
git add R/03_sensitivity.R
git commit -m "MNAR sensitivity by IPW"
git switch main
git merge sensitivity-mnar
git branch -d sensitivity-mnar

# week 8: submit
git tag -a v1.0-jbs-submission -m "Submitted to JBS 2026-06-15"
git push origin v1.0-jbs-submission

# week 22: revision request
git diff v1.0-jbs-submission main --stat
git switch --detach v1.0-jbs-submission
# rerun, compare with current main, decide what to change
git switch main
git tag -a v1.1-jbs-revision-1 -m "First revision JBS"
git push origin v1.1-jbs-revision-1

The .gitignore written on day 1 keeps rendered output, editor state, the saved workspace, and the secrets file out of every later git add .. The branch kept the sensitivity work, an inverse probability weighting (IPW) analysis, isolated until it was ready. The tags make the timeline navigable, and the remote is the off-site backup if the laptop dies.

TipVerification

Confirm that the history has the shape you intended and that the server holds your tags:

git log --oneline --decorate --graph -10
git ls-remote --tags origin

The first shows each tag beside its commit. The second lists the tags on GitHub. A tag that appears in the first and not the second was never pushed.

Question. In week 22, why switch to the tag with --detach rather than reset main to it?

Answer. Because the goal is to look, not to move. --detach leaves main, and every commit made since submission, exactly where it is. Switching back restores the current state. Resetting main to the tag would move the branch backward. It would also hide the post-submission work from git log, so that it could be recovered only through the reflog.

7.8 Rules of thumb

  1. Habit 3: version control from day one. One logical change per commit, a message that says why, and a push to a private remote at the end of each day.
  2. Habit 5: pre-specify, then tag. Tag every irreversible moment (the analysis plan, each submission, results sent to the PI), so that ‘what exactly did we report?’ has an answer.
  3. Habit 12: every model output is a hypothesis until verified. Commit or branch before an agent touches the repository, and prefer the recovery command that destroys nothing.

7.9 Cumulative practice

  1. Cumulative (uses Chapter 5 and Chapter 2). In the practice repository, add a .gitignore that excludes output/ and .Renviron, create output/table1.csv and an .Renviron with any content, and commit with git add .. Then tag the commit v1.1-compendium. Which files did the commit contain?
  2. On your own work (no key). Put a current project under Git with a .gitignore written before the first git add, push it to a private remote, and tag the last version you sent to anyone.

git show --stat v1.1-compendium lists .gitignore alone. output/table1.csv and .Renviron were ignored, and git status --ignored lists them under ‘Ignored files’. If either appears in the commit, a pattern is misspelled or the file was already tracked, which .gitignore does not undo. git rm --cached <file> untracks a file without deleting it. The same check belongs before the first commit of every real project.

7.10 Cheat sheet

Table 7.5: Git for one analyst.
Task Command
Start a repository git init -b main
See what changed git status; git diff; git diff --staged
Commit one logical change git add <file>; git commit -m "Why"
Read the history of a file git log -p <file>
Experiment on a branch git switch -c <branch>; git merge <branch>
Find leftover conflict markers git grep -n -e '<<<<<<<' -e '>>>>>>>'
Create a private remote and push gh repo create <name> --private --source=. --remote=origin; git push -u origin main
Tag a submission git tag -a v1.0 -m "..."; git push origin v1.0
Look at a tagged version git switch --detach v1.0; git switch main
Undo, safely Table 7.4; git reflog first

7.11 Further reading

7.12 Prerequisites answers

  1. Even for solo work, Git lets you roll back to any prior state and try risky refactors on a branch. It keeps a structured log of what you did, when, and why. If you push to a remote, it is also an off-site backup. The cost is a one-time learning curve. The benefit accumulates for the rest of your career, especially when ‘solo’ projects become collaborations.
  2. A commit is a snapshot of the repository at a point in time, with a parent commit, an author, a message, and a unique hash. A branch is a movable pointer to a commit, used to develop features or experiments in isolation. A tag is an immovable pointer to a commit, used to mark release points (submissions, deployments).
  3. You are in the middle of editing files but need to pull changes from the remote or switch to another branch urgently. git stash puts your uncommitted work temporarily aside, and git stash pop restores it later. This avoids committing half-finished work just to allow a branch switch. Once popped or dropped, a stash is no longer in any reflog. It can be found for a short time with git fsck --no-reflogs --unreachable, but anything that matters should be committed instead.