19  Version Control with Git and GitHub

NoteLearning Objectives

After completing this chapter, you will be able to:

  • Explain why version control is essential for research
  • Configure Git on your computer
  • Create and manage Git repositories
  • Track changes with commits
  • Work with remote repositories on GitHub
  • Use branches for parallel development
  • Publish websites using GitHub Pages

19.1 Why Version Control?

Science demands precision and reproducibility. When you publish a paper, readers should be able to understand exactly what you did and replicate your results. Yet many researchers manage their code and manuscripts with methods that would horrify their inner scientist.

Have you ever had files named like this?

analysis_final.R
analysis_final_v2.R
analysis_final_v2_REALLY_FINAL.R
analysis_final_v2_REALLY_FINAL_fixed.R
analysis_final_v2_REALLY_FINAL_fixed_AFTER_REVIEWER2.R

This ad-hoc versioning might seem harmless, but it creates real problems. Which version produced the figures in your paper? What changed between version 2 and the “REALLY_FINAL” version? If you discover an error, can you trace it back to when it was introduced?

Version control solves these problems by systematically tracking changes to files over time. It’s like having a time machine for your project—you can go back to any point in history, see exactly what changed and when, and understand why each change was made.

The concept isn’t new to science. Laboratory notebooks have always served a similar purpose: documenting what was done, when, and by whom. Version control is simply the digital equivalent for code and text, with superpowers that paper notebooks can’t match.

Version control systems provide:

Complete History. Every change is recorded. You can see what changed, when, and why.

Safe Experimentation. Try new approaches without fear. You can always return to a working version.

Collaboration. Multiple people can work on the same project without overwriting each other’s work.

Backup. Your code exists in multiple places, protecting against data loss.

Reproducibility. Tag specific versions for publications. Anyone can access exactly what you used (Blischak et al., 2016; Ram, 2013; Wilson et al., 2017).

NoteVersion Control for Papers and Beyond

While we focus on code, version control is equally valuable for manuscripts, theses, and any text-based work. Many researchers now write papers in LaTeX or Markdown and track every revision with Git. Reviewer asked you to change something, then asked you to change it back? No problem—it’s all in the history.

19.2 Git: Distributed Version Control

Git is the most widely used version control system (Chacon & Straub, 2014). Created by Linus Torvalds (who also created Linux), Git is:

  • Distributed: Every copy is a complete repository with full history
  • Fast: Operations happen locally without network delays
  • Flexible: Supports many workflows from solo to large team projects

Key Concepts

Understanding Git’s mental model (Figure 19.1) helps everything else make sense:

Figure 19.1: The Git workflow: files move from the working directory to the staging area (git add), into the local repository (git commit), up to the remote (git push), and back down (git pull)

Working Directory. The files you see and edit on your computer.

Staging Area (Index). A preparation area where you compose your next commit.

Local Repository. The .git directory containing all version history.

Remote Repository. A copy hosted elsewhere (like GitHub) for backup and collaboration.

19.3 Setting Up Git

Installation

Check if Git is already installed:

$ git --version
git version 2.43.0

If not installed:

# macOS (with Homebrew)
$ brew install git

# Ubuntu/Debian Linux
$ sudo apt-get install git

# Windows: Download from git-scm.com

Configuration

Configure your identity (this appears in your commit history):

# Set your name
$ git config --global user.name "Your Name"

# Set your email (use the same email as your GitHub account)
$ git config --global user.email "your.email@example.com"

# Set default branch name to 'main'
$ git config --global init.defaultBranch main

# Verify settings
$ git config --list
Tip

The --global flag sets these options for all repositories on your computer. You can override them per-repository by omitting --global while inside a specific repo.

19.4 Creating a Repository

Method 1: Initialize Locally

Create a new repository from an existing directory:

# Navigate to your project directory
$ cd my_project

# Initialize Git repository
$ git init

# You'll see a message about creating .git directory
Initialized empty Git repository in /home/user/my_project/.git/

Method 2: Clone from GitHub

Copy an existing repository:

# Clone a repository
$ git clone https://github.com/username/repository.git

# Clone into a specific directory
$ git clone https://github.com/username/repository.git my_local_name

19.5 Basic Git Workflow

The daily rhythm of Git involves four main commands: status, add, commit, and push. Don’t be intimidated by the number of Git commands that exist—most researchers use only a handful regularly, and you can be highly productive knowing just these four.

Think of the Git workflow like preparing a package to ship:

  1. You work on your files (working directory)
  2. You decide what to include (git add → staging area)
  3. You seal and label the package (git commit → local repository)
  4. You send it out (git push → remote repository)

Each commit is like a snapshot of your project at a moment in time, labeled with a message explaining what changed. Over time, these commits form a complete history of your project’s evolution.

Checking Status

Always start by checking your repository’s status:

$ git status
On branch main
Your branch is up to date with 'origin/main'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
        modified:   analysis.R

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        new_data.csv

no changes added to commit (use "git add" and/or "git commit -a")

Staging Changes

Add files to the staging area:

# Add specific file
$ git add analysis.R

# Add all changes in current directory
$ git add .

# Add all changes everywhere
$ git add -A

# Add only certain file types
$ git add *.R

Committing Changes

Record staged changes with a descriptive message:

$ git commit -m "Add initial data analysis script"
[main 7d4e8c2] Add initial data analysis script
 1 file changed, 45 insertions(+)
 create mode 100644 analysis.R
ImportantWrite Good Commit Messages

A good commit message:

  • Uses present tense: “Add feature” not “Added feature”
  • Is concise but descriptive
  • Explains what and why, not how
  • References issues if applicable: “Fix alignment bug (#42)”

Bad: “updates”
Good: “Add GC content calculation to genome analysis”

Viewing History

See your commit history:

# Full history
$ git log

# Condensed one-line format
$ git log --oneline

# With graph showing branches
$ git log --oneline --graph --all

# Last 5 commits
$ git log -5

# Show the actual changes (the "patch") made by each commit
$ git log -p

Each commit is identified by a unique hash (7d4e8c2 below is the short form) and records the author, date, and message, which is why a good message matters.

Example output:

$ git log --oneline
7d4e8c2 (HEAD -> main) Add initial data analysis script
3a1b2c3 Update README with project description
9f8e7d6 Initial commit

19.6 Working with GitHub

GitHub is a web-based platform for hosting Git repositories. It adds:

  • Cloud backup for your code
  • Collaboration features (issues, pull requests)
  • Project management tools
  • Free website hosting (GitHub Pages)
  • Integration with other services

For a research project specifically, GitHub gives you:

Reproducibility. The complete history of how an analysis developed, not just its final state.

Documentation. A README.md on the repository’s front page, a wiki, and GitHub Pages for a project website (Section 19.11).

Issues. A built-in tracker for bugs, ideas, and to-dos that stays with the code. Referencing an issue number in a commit message (“Fix normalization bug (#12)”) links the two.

Releases and DOIs. When you submit a paper, tag the exact version of the code it used (git tag -a v1.0 -m "Version used in manuscript"; see Section H.11) and create a release from that tag on GitHub. Connecting the repository to Zenodo turns each release into an archived copy with a citable DOI (Section E.5), which is what journals and funders increasingly ask for.

Creating a GitHub Account

  1. Go to github.com
  2. Click “Sign up”
  3. Choose a professional username
  4. Use your academic email for the Student Developer Pack
Tip

Apply for the GitHub Student Developer Pack for free access to premium features and developer tools.

Connecting Local to Remote

After creating a repository on GitHub:

# Add remote repository (origin is conventional name)
$ git remote add origin https://github.com/username/repository.git

# Verify the remote
$ git remote -v
origin  https://github.com/username/repository.git (fetch)
origin  https://github.com/username/repository.git (push)

# Make sure your branch is named 'main' before the first push
$ git branch -M main

# Push your commits to GitHub
$ git push -u origin main

The -u flag sets up tracking, so future pushes only need git push. The git branch -M main line renames your current branch to main; it is harmless if the branch already has that name, and it rescues you when an older Git created the branch as master (the init.defaultBranch setting in Section 19.3.2 makes main the default for every future repository). GitHub takes the first branch you push as the repository’s default branch, so pushing main first keeps the two sides in agreement; if a repository ever ends up with both a master and a main, change the default under Settings → Branches on GitHub.

Push and Pull

Pushing sends your local commits to GitHub:

$ git push origin main
# or simply, if tracking is set up:
$ git push

Pulling retrieves commits from GitHub:

$ git pull origin main
# or simply:
$ git pull

Fetching downloads new commits from GitHub without merging them into your files:

$ git fetch origin

# Now inspect what arrived before deciding to merge it
$ git log --oneline main..origin/main
$ git merge origin/main

The easiest way to watch pull do its job—no collaborator required—is a round trip through GitHub’s web editor: open a file on your repository’s page, click the pencil icon, make a small edit, and commit it there. Your laptop does not have that commit yet; git pull brings it down, and git log --oneline then shows both histories woven into one. This is also the habit that keeps one project in sync across two machines (say, your laptop and Talapas): always pull before you start work, always push when you stop.

git pull is exactly git fetch followed by git merge. Use fetch when you want to see what collaborators have changed before it touches your working directory—for example, when you are in the middle of something and are not sure whether the incoming changes will conflict with yours.

Warning

Always pull before starting work to get any changes from collaborators. Push frequently to back up your work.

19.7 Branching

Branches let you develop features in isolation without affecting the main codebase (Figure 19.2).

Figure 19.2: Branching allows parallel development that can later be merged: a feature branch diverges from main, collects commits, and is merged back

Creating and Switching Branches

# Create a new branch
$ git branch feature-analysis

# Switch to the branch
$ git switch feature-analysis

# Or create and switch in one command
$ git switch -c feature-analysis

# List all branches
$ git branch
* feature-analysis
  main
Notegit switch vs. git checkout

git switch was added in Git 2.23 (2019) to do one job—move between branches—clearly. The older git checkout does the same thing (git checkout feature-analysis, git checkout -b feature-analysis) and several unrelated things, such as discarding changes to a file. You will still see checkout everywhere in tutorials, Stack Overflow answers, and older scripts; it works fine, and the two are interchangeable for branch operations. This book uses switch for branches and restore for undoing file changes because each command name says what it does.

Merging Branches

When your feature is complete, merge it back to main:

# Switch to main
$ git switch main

# Merge the feature branch
$ git merge feature-analysis

# Delete the branch after merging (optional)
$ git branch -d feature-analysis

Resolving Conflicts

If Git can’t automatically merge changes, you’ll get a conflict:

$ git merge feature-branch
Auto-merging analysis.R
CONFLICT (content): Merge conflict in analysis.R
Automatic merge failed; fix conflicts and then commit the result.

The file will contain conflict markers:

<<<<<<< HEAD
# Main branch version
result <- mean(data)
=======
# Feature branch version
result <- median(data)
>>>>>>> feature-branch

To resolve:

  1. Edit the file to keep the code you want
  2. Remove the conflict markers (<<<<<<<, =======, >>>>>>>)
  3. Stage and commit the resolved file

19.8 Pull Requests

Pull requests (PRs) are GitHub’s mechanism for proposing changes and requesting code review. They’re central to collaborative workflows and open-source contributions.

Creating a Pull Request

After pushing a branch to GitHub:

  1. Navigate to your repository on GitHub
  2. You’ll see a prompt: “Compare & pull request” — click it
  3. Add a descriptive title and summary of your changes
  4. Assign reviewers if working with collaborators
  5. Click “Create pull request”

Reviewers can then:

  • Comment on specific lines of code
  • Request changes
  • Approve the PR

Once approved, click “Merge pull request” to integrate the changes into the main branch.

Tip

Pull requests aren’t just for teams! Use them on solo projects to:

  • Document significant changes with a summary
  • Review your own code before merging
  • Keep a clean history of feature additions

Pushing Branches to GitHub

To share a branch with collaborators or create a PR:

# Push a new branch to GitHub
$ git push origin feature-branch

# Delete a remote branch (note the colon)
$ git push origin :old-branch

19.9 Forking

Forking creates your own copy of someone else’s repository under your GitHub account. It’s different from cloning:

  • Clone: Direct copy linked to the original repo
  • Fork: Independent copy on your GitHub account (which you then clone)

When to Fork

  • Contributing to open-source projects
  • Using someone’s code as a starting point for your own project
  • Experimenting with changes you don’t have permission to push

Fork Workflow

  1. Click “Fork” on the GitHub repository page
  2. Clone your fork to your local machine
  3. Make changes and push to your fork
  4. Create a pull request to the original repository

This is how most open-source software is developed—outside contributors fork, improve, and submit pull requests back to the main project.

Note

Keeping a fork synchronized with the original (“upstream”) repository requires additional steps. See GitHub’s guide on Syncing a fork.

Starting from a Template Repository

Some repositories are marked as templates (course assignment scaffolds are often distributed this way). A template gives you a fresh repository that starts with the template’s files but has no connection to the original: its history begins at your first commit, and there is no upstream to sync with or open pull requests against. Use a template when you want a starting point; fork when you want to contribute changes back.

  1. On the template’s GitHub page, click the green Use this template button and choose Create a new repository
  2. Pick an owner (your account) and a name, and decide whether it should be public or private
  3. Click Create repository
  4. Clone your new repository to your computer as usual:
$ git clone git@github.com:yourname/your-new-repo.git
Table 19.1: Fork vs. template repositories
Fork Template
Shares history with the original Yes No
Can open pull requests upstream Yes No
Typical use Contributing to a project Starting your own project from a scaffold

Figure 19.3 shows the three ways to make a repository your own.

Figure 19.3: Three ways to copy a repository: a clone is a local copy linked to the original, a fork is a server-side copy that shares history and can send pull requests back upstream, and a template creates a fresh repository with no connection to the original.

19.10 The .gitignore File

Not everything should be tracked. Git keeps every version of every tracked file forever, which is ideal for code and ruinous for bulk files—and GitHub enforces the economy: a single file over 100 MB is rejected at push (warnings begin at 50 MB), and GitHub asks that repositories stay under 1 GB (5 GB at the outside). Raw data, regenerable outputs, and editor or system droppings therefore stay out of the repository; the .gitignore file specifies intentionally untracked files:

# Create .gitignore
$ touch .gitignore

Common patterns for scientific projects:

# Data files (too large or sensitive)
*.fastq
*.fastq.gz
*.bam
*.vcf
data/raw/*

# R artifacts
.Rhistory
.RData
.Rproj.user/

# Python artifacts
__pycache__/
*.pyc
.venv/
venv/
.ipynb_checkpoints/

# Output files
results/temp/*
*.log

# Quarto's working folder (regenerated on every render)
.quarto/

# System files
.DS_Store
Thumbs.db

# Credentials (NEVER commit these!)
*.pem
.env
secrets.txt

The .venv/ entry matters as soon as you follow Section 12.3, which creates a project virtual environment—hundreds of megabytes of installed packages that belong on each machine, not in the repository (rebuild them from the project’s recorded dependencies instead).

Warning

Add .gitignore early! Once files are tracked, adding them to .gitignore won’t untrack them.

19.11 GitHub Pages: Free Website Hosting

GitHub Pages turns your repository into a website—perfect for project documentation, lab websites, or personal portfolios. Figure 19.4 shows the path from Quarto source to a live site.

Figure 19.4: GitHub Pages workflow: Quarto documents are rendered to HTML, pushed to a GitHub repository, and served automatically as a website

Setting Up GitHub Pages

  1. Go to your repository on GitHub
  2. Click Settings → Pages
  3. Under “Source”, select Deploy from a branch
  4. Select branch: main and folder: /docs (or root)
  5. Click Save

Your site will be live at: https://username.github.io/repository/. The Settings → Pages screen shows the exact URL with a Visit site button once deployment finishes, and the repository’s Actions tab lists each “pages build and deployment” run—a green check means the newest push is what is being served. The repository’s name is the last part of the URL, so name repositories with their future address in mind.

Two ways to get a nicer address:

  • Name a repository exactly username.github.io and its site is served from the bare root, https://username.github.io—the conventional home for a personal academic site.
  • Use a fully custom domain (registered at any domain registrar, typically $10–20 per year): enter it under Settings → Pages → Custom domain, add the DNS record the registrar asks for (a CNAME record pointing at username.github.io), and enable Enforce HTTPS. GitHub stores the domain in a file named CNAME in the published folder; because Quarto rewrites the output folder on every render, keep a CNAME file in your project and list it under resources: in _quarto.yml so each render copies it back.

For Quarto Projects

In your _quarto.yml (see Section 16.15 for project layout):

project:
  type: website
  output-dir: docs

Then render and push:

# Render your site
$ quarto render

# Commit the docs folder
$ git add docs/
$ git commit -m "Update website"

# Push to GitHub
$ git push

The alternative: let Quarto publish for you. Quarto has a built-in publishing command that renders the site and pushes the rendered output to a separate gh-pages branch, so the generated HTML never clutters the history of main:

$ quarto publish gh-pages

The first run offers to create the gh-pages branch and configure Pages to serve from it; you can also record the target in _quarto.yml so collaborators publish the same way:

publish:
  gh-pages:
    branch: gh-pages

With this route, Pages’ source branch is gh-pages (root folder) rather than main with /docs. Pick one approach per repository and stay with it: committing docs/ keeps everything on one branch and makes the published files part of your ordinary history, while quarto publish gh-pages keeps source and output cleanly separated. Both are one command away from an updated site.

Figure 19.5 compares the two routes side by side.

Figure 19.5: Two routes to the same GitHub Pages site: committing the rendered docs/ folder on main, or letting quarto publish gh-pages push the rendered output to a separate gh-pages branch.

19.12 Best Practices

Repository Organization

project/
├── README.md          # Project description (always include!)
├── LICENSE            # How others can use your code
├── .gitignore         # Files to ignore
├── data/              # Data files (consider .gitignore for large files)
│   ├── raw/           # Original, immutable data
│   └── processed/     # Cleaned data
├── scripts/           # Analysis scripts
│   ├── 01_clean.R
│   └── 02_analyze.R
├── results/           # Output files
└── docs/              # Documentation or website

Commit Frequency

  • Commit early, commit often
  • Each commit should be a logical unit of change
  • Don’t commit half-finished work to main
  • Use branches for experimental work

Collaboration Workflow

For team projects:

  1. Pull before starting work
  2. Create a branch for your changes
  3. Make commits with clear messages
  4. Push your branch to GitHub
  5. Create a Pull Request for review
  6. After approval, merge to main

19.13 Authentication: HTTPS vs SSH

The first time you git push to GitHub, Git has to prove that you are you. GitHub removed password authentication for Git operations in 2021, so typing your GitHub password at the prompt will not work—you need one of the three methods below. Pick one and set it up once.

Option 1: SSH Keys (recommended for regular use)

SSH uses a pair of cryptographic keys: a private key that stays on your computer and a public key you give to GitHub. Once configured you never type a credential again. The same key pair can be used for logging in to Talapas (Section 20.4.1).

# 1. Generate a key pair (press Enter to accept the default location;
#    a passphrase is optional but recommended)
$ ssh-keygen -t ed25519 -C "you@uoregon.edu"

# 2. Print the PUBLIC key and copy the whole line
$ cat ~/.ssh/id_ed25519.pub
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... you@uoregon.edu

# 3. Test the connection once the key is added to GitHub (see below)
$ ssh -T git@github.com
Hi username! You've successfully authenticated, but GitHub does not provide shell access.

Between steps 2 and 3, add the public key to your account: on GitHub, go to your profile photo → Settings → SSH and GPG keys → New SSH key, paste the line you copied, give it a name such as “laptop”, and save. Then use SSH-style URLs when cloning or adding a remote:

$ git clone git@github.com:username/repository.git

# Or convert an existing HTTPS remote to SSH
$ git remote set-url origin git@github.com:username/repository.git

Never share or commit the private key (~/.ssh/id_ed25519, no .pub). GitHub’s guide on Connecting with SSH covers the details, including Windows and macOS keychain setup.

Option 2: HTTPS with a Personal Access Token

If you keep the https://github.com/... URLs, Git will prompt for a username and password. The “password” must be a personal access token, not your account password. Create one at your profile photo → Settings → Developer settings → Personal access tokens → Fine-grained tokens → Generate new token. Give it a name and expiration date, choose which repositories it may access, and under Repository permissions set Contents to Read and write. Copy the token immediately—GitHub shows it only once—and paste it when Git asks for your password. Enable credential caching (below) so you are not asked on every push.

Option 3: The GitHub CLI

The GitHub CLI (gh) can set up authentication for you interactively. Install it first (brew install gh on macOS, winget install --id GitHub.cli on Windows, sudo apt-get install gh on Ubuntu/WSL), then:

$ gh auth login
$ gh auth status    # afterwards: confirms which account is logged in

Answer the prompts (GitHub.com, HTTPS or SSH, log in with a web browser), and gh stores the credential and configures Git to use it. This is often the quickest route on a new machine.

Credential Caching (HTTPS)

Avoid entering credentials repeatedly:

# Cache credentials for 1 hour (3600 seconds)
$ git config --global credential.helper 'cache --timeout=3600'

# On macOS, use the keychain
$ git config --global credential.helper osxkeychain

# On Windows, use the credential manager
$ git config --global credential.helper manager

19.14 Line Endings Across Operating Systems

Different operating systems use different characters to mark line endings:

  • Linux/macOS: LF (Line Feed)
  • Windows: CRLF (Carriage Return + Line Feed)

This can cause Git to show changes on lines you didn’t edit when collaborating across operating systems.

Solution

Configure Git to handle line endings automatically:

# On macOS/Linux
$ git config --global core.autocrlf input

# On Windows
$ git config --global core.autocrlf true

19.15 Temporarily Saving Changes: Git Stash

Sometimes you need to switch branches but aren’t ready to commit your current changes. git stash temporarily saves your work:

# Stash current changes
$ git stash

# List stashed changes
$ git stash list

# Restore most recent stash
$ git stash pop

# Restore a specific stash
$ git stash apply stash@{2}

# Delete a stash
$ git stash drop stash@{0}

This is useful when you need to quickly switch context—perhaps to fix an urgent bug on another branch—without committing incomplete work.

19.16 Troubleshooting

Common Issues and Solutions

Q: I made changes to the wrong branch!

# Stash your changes
$ git stash

# Switch to correct branch (older syntax: git checkout correct-branch)
$ git switch correct-branch

# Apply the stashed changes
$ git stash pop

Q: I edited a file and want to throw away my changes

# Discard unstaged changes to one file, restoring the last committed version
$ git restore analysis.R

# Un-stage a file you added by mistake (keeps your edits)
$ git restore --staged analysis.R

git restore is the modern command for this job; the older syntax you will still see is git checkout -- analysis.R. Either way, discarded changes are gone for good, so be sure before you run it.

Q: I want to undo my last commit (but keep the changes)

$ git reset --soft HEAD~1

Q: I committed something I shouldn’t have

# Remove file from Git but keep it locally
$ git rm --cached sensitive_file.txt
$ git commit -m "Remove sensitive file from tracking"

Q: Everything is broken!

When all else fails, you can always clone a fresh copy:

# Save your current work somewhere safe first!
$ cp -r my_project my_project_backup

# Clone fresh from GitHub
$ git clone https://github.com/username/repository.git my_project_fresh
Tip

For more Git emergencies, visit ohshitgit.com — a humorous but genuinely helpful resource for common Git mistakes.

When to Commit?

Commit early and often. A good rule of thumb:

  • Commit when you’ve completed a logical unit of work
  • Commit before trying something experimental
  • Commit at the end of each work session
  • If you’re asking “should I commit?” — the answer is usually yes

19.17 Useful Commands Reference

Table 19.2 collects the commands used in this chapter.

Table 19.2: Essential Git commands
Command Description
git init Initialize new repository
git clone <url> Copy remote repository
git status Show current state
git add <file> Stage changes
git commit -m "msg" Record staged changes
git push Upload to remote
git pull Download from remote and merge
git fetch Download from remote without merging
git branch List branches
git switch <name> Switch to a branch
git switch -c <name> Create and switch branch (older syntax: git checkout -b <name>)
git restore <file> Discard unstaged changes to a file (older syntax: git checkout -- <file>)
git merge <branch> Merge branch
git log --oneline View commit history
git log -p View history with the changes in each commit
git diff Show unstaged changes
git stash Temporarily store changes
git help <command> Open the manual page for any command (e.g. git help log)

For a comprehensive reference of Git commands and workflows, see Appendix H.

19.18 Running Example: Your Course Website

NoteRunning example

This section ties the chapter together with the Week 8 class activity: putting the Quarto website you built in Chapter 16 under version control and publishing it with GitHub Pages. It uses nothing beyond what this chapter has already covered—git init (Section 19.4.1), the basic workflow (Section 19.5), connecting to a remote (Section 19.6.2), and Pages (Section 19.11).

Route 1: your own website, from scratch. This is the in-class route: you already have a website project (the personalized example_website from the Quarto chapter), and it becomes a repository and then a live site.

$ cd ~/projects/my_website
$ quarto render                 # writes the site into docs/ (output-dir: docs)
$ touch docs/.nojekyll          # tell GitHub Pages to serve the files as-is
$ git init
$ git add .
$ git commit -m "First commit: my academic website"
$ git branch -M main

On GitHub, create a new, empty repository (no README, no license—those would start a history that conflicts with yours), then connect and push exactly as in Section 19.6.2 (git remote add origin ..., git push -u origin main). Finally turn on Pages: Settings → Pages → Deploy from a branch → main, /docs. A minute later the site is live at https://yourname.github.io/my_website/.

Route 2: start from the course template. The course also provides a template website repository at https://github.com/wcresko/academic_website_template: a small Quarto website project whose pages are ordinary .qmd files. The workflow from template to live site exercises the same Git skills in the other direction—the repository starts on GitHub and comes down to your machine.

  1. Create your copy. Log in to GitHub (this matters—the button does not appear otherwise), open the template repository, and click the green Use this template button, then Create a new repository. Pick your account as the owner and give it a name. Because this is a template rather than a fork, your new repository starts with the template’s files but a fresh history (Table 19.1).

  2. Clone it. On your new repository’s page, use the green Code button to copy the repository’s URL, then, in a terminal, cd to wherever you keep projects and clone it:

    $ git clone git@github.com:yourname/your-website-repo.git
    $ cd your-website-repo

    (Use the https://... URL instead if you set up a personal access token rather than an SSH key; see Section 19.13.)

  3. Edit and render. Open the folder in VS Code, Positron, or RStudio and edit the .qmd files—they accept everything from Chapter 16, including R and Python chunks. The project’s _quarto.yml sets output-dir: docs, so quarto render writes the finished site into docs/.

  4. Commit and push. The daily rhythm from Section 19.5:

    $ git status
    $ git add .
    $ git commit -m "Personalize site content"
    $ git push
  5. Turn on Pages. On GitHub: Settings → Pages, source Deploy from a branch, branch main, folder /docs, and Save. After a minute or two your site is live at https://yourname.github.io/your-website-repo/.

From here on, updating the site is steps 3 and 4 plus a push: edit, quarto render, commit, push. Every published version of the site corresponds to a commit, which is the whole point—when something breaks, git log tells you exactly which change broke it.

19.19 Summary

Version control with Git and GitHub is essential for modern research:

  • Git tracks all changes to your files with complete history
  • The workflow is: edit → stage → commit → push
  • Branches enable parallel development and experimentation
  • GitHub provides cloud hosting, collaboration, and free websites
  • Good practices include meaningful commits, .gitignore, and regular pushing

Learning Git has a steep initial curve, but the investment pays dividends throughout your career. Start simple, use it consistently, and gradually adopt more advanced features.

Tip

For a complete reference of Git commands with detailed syntax and workflows, see Appendix H.

Additional Reading

Exercises

TipPractice Exercises

Exercise 1: First Repository

  1. Create a new directory for a test project
  2. Initialize it as a Git repository
  3. Create a README.md file with a project description
  4. Stage and commit the file
  5. View your commit history

Exercise 2: GitHub Integration

  1. Create a new repository on GitHub (don’t initialize with README)
  2. Connect your local repository to GitHub
  3. Push your commits
  4. Verify your files appear on GitHub

Exercise 3: Branching Practice

  1. Create a branch called add-analysis
  2. Add a new script file on that branch
  3. Commit your changes
  4. Switch back to main
  5. Merge the branch
  6. Delete the branch

Exercise 4: Collaboration Simulation

  1. Clone a repository (your own or a public one)
  2. Make changes on GitHub directly (edit a file in the browser)
  3. Pull those changes to your local repository
  4. Make local changes and push them back