BudiBadu Logo
Samplebadu

Git by Example: Repository Initialization

2.43.0

Learn how to start a new Git repository using the git init command. This example explains what happens under the hood when you initialize a project and how to prepare your directory for version control.

Code

# Navigate to your project directory
cd /path/to/your/project

# Initialize a new Git repository
git init

# Output:
# Initialized empty Git repository in /path/to/your/project/.git/

# Check the status of your new repository
git status

# Output:
# On branch master
#
# No commits yet
#
# nothing to commit (create/copy files and use "git add" to track)

Explanation

Initializing a Git repository is the first step in tracking your project's history. The git init command transforms your current directory into a Git repository by creating a hidden .git subdirectory. This directory houses all the metadata and object database that Git uses to manage version control.

When you run this command, Git sets up the necessary internal structures but does not automatically track existing files. You start with an empty staging area, and you must explicitly add files using git add before they can be committed. This gives you control over exactly what gets included in your project's history.

This command can be used to start a fresh project or to convert an existing, unversioned project into a Git repository. It is a local operation that prepares your workspace for all subsequent Git commands.

  • Creates a .git directory for metadata
  • Sets up the default branch (usually master or main)
  • Does not modify your project files
  • Prepares the directory for git add and git commit

Code Breakdown

2
Changes the current working directory to your project folder. It is important to be in the root directory of your project before initializing Git.
5
Executes the initialization command. This creates the hidden .git folder and sets up the repository structure. If the directory was already a Git repository, this command is safe to run again (it re-initializes).
8
Shows the confirmation message indicating where the Git repository was initialized. The path ends in /.git/, confirming the location of the metadata directory.
11
Checks the current state of the repository. Since this is a fresh init, it reports that you are on the default branch (master/main) and have no commits yet.