Git Init

The git init command creates a new Git repository. You run it one time inside a project folder, and from then Git can track the files of that folder.

Syntax

git init
git init project-name

Create a new repository

Terminal output

$ mkdir my-website
$ cd my-website
$ git init
Initialized empty Git repository in /home/robin/my-website/.git/
$ git status
On branch main

No commits yet

nothing to commit (create/copy files and use "git add" to track)

Git created a hidden folder named .git in the project. That folder is the repository. If you delete it, you delete the full history, but your normal files stay.

Initialize a repository in a new folder directly

You can give a folder name, and Git will create the folder and run init inside it.

Terminal output

$ cd ..
$ git init blog
Initialized empty Git repository in /home/robin/blog/.git/
$ ls -a blog
.
..
.git

What is inside the .git folder?

Terminal output

$ cd my-website
$ ls .git
HEAD
config
description
hooks
info
objects
refs

NamePurpose
HEADA file which points to the current branch
configSettings of this repository only
objects/Where Git stores all the content (files and commits)
refs/Branch and tag names, and the commit they point to
hooks/Sample scripts which run on Git events

Never edit the files of .git by hand, unless you know exactly what you are doing.

Bare repository

A normal repository has the working files plus the .git folder. A bare repository has only the Git data and no working files. It is used on servers as the central place to push to, like the repository on GitHub.

Terminal output

$ git init –bare ../server.git
Initialized empty Git repository in /home/robin/server.git/
$ ls ../server.git
HEAD
config
description
hooks
info
objects
refs

Use git init on a project that already has files

If you already have a folder with files, go inside it and run git init. The files will be shown as untracked, and then you can add and commit them.

Common mistakes

  • Running git init inside another repository, which creates a repository inside a repository. Check first with git status.
  • Running it in the home folder by mistake, so Git starts tracking everything. Always check the folder with pwd before.
Note: If you want to start from an existing project on the internet, use git clone instead of init.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Check the status of files in a Git repository
Stage only selected files and commit them separately
Show the commit history in one line per commit
See the changes of a file before staging and before commit
Ignore all .log files with .gitignore
Unstage a file
Delete a file with git rm
Interview Questions & Answers
How can you add files to Git?
How can you commit a file in Git?
What are the common files to ignore in Git?
How to remove untracked files in Git?
What is the staging area in Git?
What is the difference between git add and git commit?
What is HEAD in Git?