Lesson 2: Initializing a Local Git Repository
This lesson covers how to create a local Git repository, track files, and push changes to GitHub.
Step 1: Creating a New Local Repository
- Open a terminal and navigate to the directory where you want to create a new project:
cd ~/projects # Change to your preferred location
mkdir my-first-repo # Create a new directory
cd my-first-repo # Enter the directory - Initialize an empty Git repository:
git init- This sets up a
.git/folder, which tracks changes inside this directory. - You will see the message:
Initialized empty Git repository in /path/to/my-first-repo/.git/
- This sets up a
Step 2: Adding and Committing Files Locally
-
Create a file inside the repository:
echo "My first Git-tracked file" > file.txt -
Check the repository status:
git status- This will show
file.txtas untracked.
- This will show
-
Add the file to Git's tracking system:
git add file.txt -
Commit the file with a descriptive message:
git commit -m "Initial commit: Added file.txt"- This saves the change history locally, but it is not yet uploaded to GitHub.
Step 3: Connecting to a GitHub Repository
To push your local repository to GitHub:
- Go to GitHub and create a new repository (without initializing a README).
- Copy the repository URL (e.g.,
https://github.com/your-username/my-first-repo.git). - Link the local repository to GitHub:
git remote add origin https://github.com/your-username/my-first-repo.git - Push the local repository to GitHub:
git push -u origin main- This uploads all committed changes to GitHub.
- The
-uflag setsorigin mainas the default push destination.