Creating repositories¶
What is a Git repository?¶
A Git repository (or repo) is a directory that contains:
- your files and subdirectories, the actual project content;
- Git storage, a hidden
.gitdirectory where Git keeps the full history and its own information about the project.
homelab/ <- the repository (project directory)
├── README.md <- file
├── inventory.csv <- file
├── docs/ <- sub-directory
└── .git/ <- Git storage (hidden)
The files and subdirectories are what you work on. The .git directory is what makes the directory a repository: it holds every recorded version, the staging area, and the repository configuration.
Do not edit .git
Never edit, move, or delete files inside .git by hand. Git manages this directory itself, and changing it manually can corrupt the repository. Deleting .git removes the whole history: the directory becomes an ordinary folder again.
Benefits of repositories¶
- Systematically track versions of every file in the project.
- Revert to previous versions when something goes wrong.
- Compare versions at different points in time.
- Collaborate with colleagues, because everyone works from the same history.
Two ways to create a repository¶
git init creates a repository. Which form to use depends on whether the project directory already exists:
flowchart TD
q{"Does the project<br/>directory exist?"}
q -- "No, new project" --> a["git init homelab<br/>creates homelab/ and homelab/.git/"]
a --> cd["cd homelab"]
q -- "Yes, existing files" --> b["cd homelab<br/>git init<br/>adds .git/ to the current directory"]
cd --> s["git status"]
b --> s
Creating a new repository¶
To start a brand-new project, pass a name to git init. Git creates a directory with that name and initializes a repository inside it:
$ git init homelab
Initialized empty Git repository in /home/sam/homelab/.git/
$ cd homelab
$ git status
On branch main
No commits yet
nothing to commit (create/copy files and use "git add" to track)
| Command | Effect |
|---|---|
git init homelab |
Creates the homelab directory and the .git storage inside it |
cd homelab |
Moves into the new repository. Git commands act on the repository you are in |
git status |
Reports the state of the repository: current branch, commits, and file changes |
Here git status reports that the repository is on branch main, that nothing has been recorded yet (No commits yet), and that there are no files to record.
Converting an existing project into a repository¶
If the project directory already exists, move into it and run git init without a name. The current directory becomes the repository:
$ cd /home/sam/homelab
$ git init
Initialized empty Git repository in /home/sam/homelab/.git/
Your existing files are not modified: Git only adds the .git directory. Running git init again in an existing repository is safe and does not overwrite what is already there (git init documentation).
| Syntax | Use it when |
|---|---|
git init <directory> |
Starting a new project from scratch |
git init |
The project directory already exists and you are inside it |
What is being tracked?¶
Right after git init in a directory that already contains files, git status lists them as untracked:
$ git status
On branch main
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
README.md
inventory.csv
nothing added to commit but untracked files present (use "git add" to track)
Git has noticed files in the directory that it is not tracking yet. An untracked file exists in the directory, but Git is not recording its versions. Git never starts tracking a file automatically: you have to add it explicitly, which is the subject of the next page. Git also gives a hint in parentheses: use "git add" to track.
Read git status often
git status changes nothing; it only reports. Run it whenever you are unsure what state the repository is in, and read the hints it prints: they usually tell you which command to use next.
The initial branch name: main or master¶
When a repository is created, Git also creates its first branch. Its name depends on your configuration: without any setting, Git currently names it master, and this default will change to main in Git 3.0 (git init documentation). GitHub names the default branch of new repositories main, and so do these notes.
You can choose the name in two ways:
# Choose the name for one repository
git init -b main homelab
# Or change the default for all new repositories (user-wide setting)
git config --global init.defaultBranch main
Both names work the same way; only the name differs. The labs use git init -b main, so they behave the same whatever your configuration.
Nested repositories¶
Do not create a Git repository inside another Git repository. This is called a nested repository.
homelab/
├── .git/ <- repository 1
├── README.md
└── scripts/
├── .git/ <- repository 2, nested inside repository 1
└── backup.sh <- recorded by which repository?
With two .git directories, it becomes unclear which repository should record changes to scripts/backup.sh. In practice, the outer repository does not track the inner repository's files as ordinary files. This is confusing and easy to get wrong.
Common mistake: running git init in your home directory or in a parent folder "to be safe", then again in each project. Before running git init, run git status. If it prints fatal: not a git repository, you are not inside a repository and can safely create one.
Note
Git does provide an official mechanism for including one repository inside another, called submodules. It is an advanced topic, not covered here.
Hands-on labs¶
Three labs, from guided to more autonomous. Each one has its own setup, so you can do them in any order and repeat them as often as you like. Type the commands rather than pasting them, and read every output before moving on: the goal is to build reflexes, not to reach the end.
Lab 1: create two repositories¶
Objective: create one repository from scratch and convert one existing project into a repository, then check what Git is tracking.
Prerequisites and initial state: Git installed. Everything happens in ~/git-practice/repos, which must not be inside an existing repository.
Setup:
mkdir -p ~/git-practice/repos
cd ~/git-practice/repos
git status # must print "fatal: not a git repository ..."
mkdir -p homelab/docs
echo "# Homelab" > homelab/README.md
echo "hostname,ip,role" > homelab/inventory.csv
echo "# Network" > homelab/docs/network.md
Tasks:
- From
~/git-practice/repos, create a new, empty repository calleddotfileswhose first branch is namedmain, and check its status. - Convert the existing
homelabdirectory into a repository, withmainas its first branch. - Check which files Git sees in
homelab, and whether they are tracked. - Confirm that each repository has its own
.gitdirectory and that the two repositories are not nested.
Expected result and verification:
git statusindotfilesshowsNo commits yetandnothing to commit.git statusinhomelablistsREADME.md,docs/, andinventory.csvunderUntracked files.ls -ashows a.gitdirectory in each project, and~/git-practice/repositself is not a repository (git statusthere still fails).
Solution
cd ~/git-practice/repos
# 1. New repository from scratch
git init -b main dotfiles
cd dotfiles
git status # On branch main / No commits yet / nothing to commit
cd ..
# 2. Convert an existing directory
cd homelab
git init -b main # no name: the current directory becomes the repository
# 3. What is tracked?
git status # README.md, docs/ and inventory.csv are untracked
cd ..
# 4. Checks
ls -a dotfiles homelab # both contain .git
git status # still "fatal: not a git repository" in ~/git-practice/repos
git init <name>creates the directory, whilegit initalone uses the current directory.-b mainsets the name of the first branch. Without it, Git usesmasterunlessinit.defaultBranchis configured.- The files in
homelabare untracked: Git sees them but will not record them until they are added withgit add. A directory such asdocs/is listed once, as a whole. - The repositories are siblings, not nested: neither one is inside the other, and their parent directory is not a repository.
Clean up when you are done: rm -rf ~/git-practice/repos.
Lab 2: change your mind¶
Objective: run git init again on an existing repository, then remove a repository without losing your files, and create it again.
Prerequisites and initial state: Git installed. The setup creates a homelab directory with a README, not yet a repository.
Setup:
mkdir -p ~/git-practice/reinit/homelab && cd ~/git-practice/reinit/homelab
echo "# Homelab" > README.md
Tasks:
- Turn
homelabinto a repository whose first branch is calledtrunk. Check which branch you are on. - Second thoughts: run
git init -b mainin the same directory. Read the two lines Git prints. Is anything lost? Did the branch name change? - You really want
main. Remove the repository, but keepREADME.md. Hint: everything Git knows about this project lives in one hidden directory. - Check that
homelabis no longer a repository and thatREADME.mdis still there. - Create the repository again, with
mainas its first branch, and check its status.
Expected result and verification:
- Task 1:
git statusstarts withOn branch trunk. - Task 2 prints
warning: re-init: ignored --initial-branch=mainandReinitialized existing Git repository in ....git statusstill saysOn branch trunk. - Task 4:
git statusfails withfatal: not a git repository, andlsstill showsREADME.md. - Task 5:
git statussaysOn branch mainand listsREADME.mdas untracked.
Solution
# 1. First attempt
git init -b trunk
git status # On branch trunk
# 2. Running git init again is harmless
git init -b main # warning: re-init: ignored --initial-branch=main
# Reinitialized existing Git repository in .../homelab/.git/
git status # still On branch trunk
# 3. Delete the repository, not the project
ls -a # . .. .git README.md
rm -rf .git
# 4. Checks
git status # fatal: not a git repository ...
ls # README.md
# 5. Start again
git init -b main
git status # On branch main, README.md untracked
git initon an existing repository only "reinitializes" it: it adds what is missing and never deletes history. It is safe, but it does not rename the branch.- The
.gitdirectory is the repository. Deleting it removes all the history Git recorded, but leaves your files in place. - Here the history was empty, so nothing was lost. On a real project,
rm -rf .gitthrows away every commit: think twice before running it.
Clean up when you are done: rm -rf ~/git-practice/reinit.
Lab 3: the nested repository trap¶
Objective: see how Git finds the repository you are in, fall into the nested repository trap on purpose, and get out of it.
Prerequisites and initial state: Git installed. The setup creates a homelab repository with two subdirectories, docs and scripts.
Setup:
mkdir -p ~/git-practice/nested && cd ~/git-practice/nested
git init -q -b main homelab
cd homelab
mkdir docs scripts
echo "# Network" > docs/network.md
echo '#!/bin/sh' > scripts/backup.sh
Tasks:
- Go into
scriptsand rungit status. There is no.gitinscripts: which repository answers? - Make the classic mistake on purpose: run
git init -b maininsidescripts. Rungit statusagain, inscripts, then inhomelab. What changed? - Still in
homelab, try to stage everything withgit add .. Read the error. - Prove that there are now two repositories.
- Fix the mistake: remove the inner repository, keep
backup.sh, and check thatgit add .works fromhomelab.
Expected result and verification:
- Task 1:
On branch main, with../docs/and./as untracked: the paths are relative toscripts, but the repository ishomelab. - Task 2: in
scripts, onlybackup.shis listed. Inhomelab,scripts/is still listed, but it now hides a separate repository. - Task 3 fails with
error: 'scripts/' does not have a commit checked out. - Task 4:
ls -ashows a.gitdirectory both inhomelaband inscripts. - After task 5,
git statusinhomelablistsdocs/network.mdandscripts/backup.shunderChanges to be committed.
Solution
# 1. Git looks for .git in the current directory, then in each parent
cd scripts
git status # On branch main ... ../docs/ and ./ untracked
# 2. The mistake
git init -b main
git status # only backup.sh: this is the new, inner repository
cd ..
git status # docs/ and scripts/: the outer repository
# 3. The outer repository cannot add the inner one as ordinary files
git add . # error: 'scripts/' does not have a commit checked out
# 4. Two .git directories
ls -a # .git docs scripts
ls -a scripts # .git backup.sh
# 5. Remove the inner repository only
rm -rf scripts/.git
git add .
git status # new file: docs/network.md, new file: scripts/backup.sh
- Git commands work from any subdirectory of a repository: Git walks up the tree until it finds a
.gitdirectory. - After the mistake, the inner repository "wins" inside
scripts, and the outer one no longer seesbackup.shas an ordinary file. - The fix is the same as in Lab 2: removing a
.gitdirectory removes a repository, not the files. - Before any
git init, agit statusthat printsfatal: not a git repositorytells you that you are not already inside a repository.
Clean up when you are done: rm -rf ~/git-practice/nested.