Git records every change to your files as a commit with an author, a message, and a hash; GitHub (or GitLab, or Bitbucket) hosts a shared copy that a team reviews and merges into. Setting both up well takes ten minutes and prevents the two most common early disasters: a secret pushed to a public repository, and a push that fails because GitHub does not know your key. This lesson follows one person from a fresh laptop to a reviewed, merged pull request: identity, sensible defaults, an SSH key for GitHub, a repository with a .gitignore, a commit, a branch, a push, and a review.
Difficulty: Beginner · Know this first: Lesson 04
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes from a fresh laptop to a merged first pull request. It is a worked example, not a measurement. The .gitignore and push hops decide whether the change is safe and whether it gets there at all.
Pick whether the repository has a .gitignore, whether your public key is on GitHub, and how you stage files.
Three questions. No score is saved anywhere — this is just you against the material.
Git grows in four levels: recording your own work, collaborating on branches, keeping history clean and safe, and running a repository for a team.
At the basic level Git is your undo history.
Where it breaks: git add . without reading what it added.
Try it: Basic
Git refuses to commit with "Please tell me who you are". Why?
Now do it: Set your identity and check it.
At the intermediate level you work with others through branches.
Try it: Intermediate
Your pull request has a conflict with main. What do you do?
Now do it: Practise a conflict in a lab repository.
At the advanced level the repository protects itself.
Try it: Advanced
A bad commit is already on main. How do you undo it?
Now do it: Revert a commit in a lab repository.
At the master level the repository encodes how the team works.
Trade-off: required reviews and checks slow every change a little and stop the occasional disaster; tune them so small, safe changes stay fast.
Try it: Master
Why protect the main branch?
Now do it: Check the branch protection on one of your repositories.
A starting global Git configuration (~/.gitconfig), with a separate identity for work repositories:
[user]
name = Asha Rao
email = 12345678+asha-rao@users.noreply.github.com
[init]
defaultBranch = main
[core]
editor = nano
autocrlf = input
[pull]
rebase = false
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work # sets user.email to the work address
Secret scanning: GitHub's push protection blocks pushes containing many known secret formats; locally, tools such as gitleaks can run as a pre-commit hook. If a secret is pushed: revoke it at its issuer first, replace it, then remove it from history (git filter-repo) and ask the host to purge caches. The order matters, because the secret may already be copied.
HTTPS instead of SSH: gh auth login (the GitHub CLI) or Git Credential Manager stores a token securely. Never write a token into the remote URL, where it ends up in shell history and in .git/config.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A demo repository.
Push protection and secret scanning on every repository, a pre-commit secret scan in the team template, short-lived credentials instead of long-lived access keys, and budget alerts on every cloud account.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: Git 2.32 or newer (git --version; install with sudo apt install -y git or brew install git) and Python 3. A GitHub account is only needed for the last part of the lesson, not for this lab.
Type each one, read what it prints, and compare it with the note above it.
Set an identity and defaults in a lab-only config file, so your real Git settings stay untouched.
mkdir -p ~/labs/git-setup && cd ~/labs/git-setup export GIT_CONFIG_GLOBAL=~/labs/git-setup/gitconfig git config --global user.name "Asha Lab" git config --global user.email "asha@example.com" git config --global init.defaultBranch main git config --global --list
Create a repository with a .gitignore, an app, and a secret, and watch what Git would commit.
export GIT_AUTHOR_DATE="2026-01-05T09:00:00Z" GIT_COMMITTER_DATE="2026-01-05T09:00:00Z"
git init -q -b main app && cd app
printf '.env\n*.log\n__pycache__/\n' > .gitignore
printf 'print("hello")\n' > app.py
printf 'API_KEY=not-a-real-key\n' > .env
git status --short
git add . && git status --shortCommit, and ask Git which rule keeps .env out.
git commit -q -m "First commit" && git log --oneline git check-ignore -v .env
A branch, a change, and a merge back into main.
git switch -q -c feature/greeting
printf 'print("hello, team")\n' > app.py
git commit -qam "Friendlier greeting"
git switch -q main && git merge -q feature/greeting && git log --oneline --graphAdd a remote, the way you would before the first push. Nothing is contacted.
git remote add origin git@github.com:example/app.git git remote -v
Clean up.
cd ~ && rm -rf ~/labs/git-setup unset GIT_CONFIG_GLOBAL GIT_AUTHOR_DATE GIT_COMMITTER_DATE ls ~/labs
staged_check.pyThis program is a tiny pre-commit check: given the files about to be committed and their contents, it flags names that should be ignored and contents that look like secrets, the way secret-scanning tools do, before anything leaves your machine. Save it as staged_check.py, then run it.
# staged_check.py
import re
STAGED = {
"app.py": 'print("hello")\n',
"config/settings.py": 'DEBUG = False\nTIMEOUT = 30\n',
".env": "API_KEY=sk_live_51HbQ2xEXAMPLEonly7Zq\n",
"deploy/key.pem": "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA\n-----END OPENSSH PRIVATE KEY-----\n",
"notes.txt": "call the vendor about the token rotation\n",
}
NEVER = [r"(^|/)\.env$", r"\.pem$", r"(^|/)id_(rsa|ed25519)$", r"\.log$"]
SECRETS = {
"private key": r"-----BEGIN [A-Z ]*PRIVATE KEY-----",
"live API key": r"\bsk_live_[0-9A-Za-z]{16,}",
"AWS access key ID": r"\bAKIA[0-9A-Z]{16}\b",
}
problems = 0
for name, text in STAGED.items():
bad_name = any(re.search(p, name) for p in NEVER)
found = [label for label, p in SECRETS.items() if re.search(p, text)]
if bad_name or found:
problems += 1
why = ", ".join((["file name should be in .gitignore"] if bad_name else []) + found)
print(f"BLOCK {name:<20} {why}")
else:
print(f"ok {name}")
print()
print(f"{problems} file(s) blocked:", "unstage them (git rm --cached FILE) and add them to .gitignore" if problems else "safe to commit")
Run it, and you should see this output:
$ python3 staged_check.py ok app.py ok config/settings.py BLOCK .env file name should be in .gitignore, live API key BLOCK deploy/key.pem file name should be in .gitignore, private key ok notes.txt 2 file(s) blocked: unstage them (git rm --cached FILE) and add them to .gitignore
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/git-and-github-setup-identity-ssh-keys-and-first-repository && cd ~/labs/git-and-github-setup-identity-ssh-keys-and-first-repository) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Git and GitHub Setup: Identity, SSH Keys, .gitignore, and Your First Pull Request", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Set an identity and defaults in a lab-only config file, so your real Git settings stay untouched.'
'Create a repository with a .gitignore, an app, and a secret, and watch what Git would commit.'
'Commit, and ask Git which rule keeps .env out.'
'A branch, a change, and a merge back into main.'
'Add a remote, the way you would before the first push. Nothing is contacted.'
'Clean up.'
)
step_1() {
mkdir -p ~/labs/git-setup && cd ~/labs/git-setup
export GIT_CONFIG_GLOBAL=~/labs/git-setup/gitconfig
git config --global user.name "Asha Lab"
git config --global user.email "asha@example.com"
git config --global init.defaultBranch main
git config --global --list
}
step_2() {
export GIT_AUTHOR_DATE="2026-01-05T09:00:00Z" GIT_COMMITTER_DATE="2026-01-05T09:00:00Z"
git init -q -b main app && cd app
printf '.env\n*.log\n__pycache__/\n' > .gitignore
printf 'print("hello")\n' > app.py
printf 'API_KEY=not-a-real-key\n' > .env
git status --short
git add . && git status --short
}
step_3() {
git commit -q -m "First commit" && git log --oneline
git check-ignore -v .env
}
step_4() {
git switch -q -c feature/greeting
printf 'print("hello, team")\n' > app.py
git commit -qam "Friendlier greeting"
git switch -q main && git merge -q feature/greeting && git log --oneline --graph
}
step_5() {
git remote add origin git@github.com:example/app.git
git remote -v
}
step_6() {
cd ~ && rm -rf ~/labs/git-setup
unset GIT_CONFIG_GLOBAL GIT_AUTHOR_DATE GIT_COMMITTER_DATE
ls ~/labs
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
mkdir, rm, ls, cd, Redirection, If...Else, Variables.You are setting up the Git workflow for a new team of six with a mix of new and experienced engineers. Design the setup guide and repository rules.
What does each person configure? How do they authenticate to the host? What goes in every repository from day one? How are secrets kept out? What are the rules for main? How is a bad change undone?
Say six engineers, 10 repositories, and about 40 pull requests a week.
A setup guide with identity, defaults, an SSH key tested with ssh -T or gh auth login; a repository template with .gitignore, a pre-commit secret scan, a pull request template, and CODEOWNERS; push protection and secret scanning on; main protected with one review and passing CI; git revert for undoing changes on main; a written procedure for leaked secrets that starts with revoking them.
Required reviews add waiting time to every change; pairing, small pull requests, and clear owners keep that wait short.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Secret pushed | Hop 5: .gitignore | Breaks | No .gitignore. The project has a .env file with a real payment-provider API key for local testing. git add . stages it with everything else; nobody reads the staged list. |
| Secret pushed | Hop 6: Commit | Breaks | The commit contains app.py and .env. |
| Secret pushed | Hop 8: Push | Breaks | Pushed to a public repository. Within minutes an automated scanner finds the key; the payment provider's own scanning flags it too. |
| Push rejected | Hop 3: SSH key | Degrades | Key generated; the public half was never pasted into GitHub, and ssh -T was not run. |
| Push rejected | Hop 8: Push | Breaks | git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. The key is not on GitHub and the agent has nothing loaded. 25 minutes of searching end with ssh -T git@github.com, which says the same thing in one line. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.