DEV Community

Programming Entry Level: learn git

Understanding Learn Git for Beginners

Have you ever worked on a project and wished you could go back to a previous version? Or maybe collaborate with others without overwriting each other’s work? That’s where Git comes in! Git is a version control system that’s essential for almost every software developer. It’s a skill you’ll encounter in almost every job interview, and mastering it will make your life as a programmer much easier. This post will give you a friendly introduction to Git, covering the basics you need to get started.

Understanding "Learn Git"

Imagine you're writing a story. You write a draft, then decide to change a few things. Instead of directly editing the original, you make a copy to experiment with. If you like the changes, you replace the original with the copy. If not, you still have the original!

Git works similarly. It tracks changes to your files over time, allowing you to revert to previous versions, compare changes, and collaborate with others.

Think of it like this:

  • Repository (Repo): This is like the folder containing your project and all its history.
  • Commit: This is like saving a snapshot of your project at a specific point in time. Each commit has a message describing the changes you made.
  • Branch: This is like creating a separate copy of your project to work on new features or bug fixes without affecting the main project.
  • Merge: This is like combining the changes from a branch back into the main project.

Here's a simple diagram to visualize this:

graph LR
    A[Initial Commit] --> B(Branch: New Feature);
    A --> C(Branch: Bug Fix);
    B --> D[Commit on New Feature];
    C --> E[Commit on Bug Fix];
    D --> F{Merge New Feature};
    E --> F;
    F --> G[Final Commit];
Enter fullscreen mode Exit fullscreen mode

This diagram shows how you can work on multiple features or fixes simultaneously using branches, and then merge them back into the main project.

Basic Code Example

Let's see how this looks in practice. First, you'll need to install Git. You can find instructions for your operating system here: http://git-scm.com/downloads

Once installed, open your terminal or command prompt and navigate to your project directory.

  1. Initialize a Git repository:
git init
Enter fullscreen mode Exit fullscreen mode

This command creates a hidden .git folder in your project directory, which is where Git stores all the version control information.

  1. Stage your changes:
git add .
Enter fullscreen mode Exit fullscreen mode

This command tells Git to track the changes you've made to your files. The . means "add all files in the current directory."

  1. Commit your changes:
git commit -m "Initial commit: Added project files"
Enter fullscreen mode Exit fullscreen mode

This command creates a snapshot of your staged changes and saves it to the repository. The -m flag allows you to add a commit message describing the changes. Always write clear and concise commit messages!

  1. Check the status:
git status
Enter fullscreen mode Exit fullscreen mode

This command shows you the current status of your repository, including any untracked files or changes that haven't been committed.

Common Mistakes or Misunderstandings

Here are a few common mistakes beginners make with Git:

❌ Incorrectly adding files:

git add file.txt
git commit -m "Added file"
git add another_file.txt # Oops! Forgot this one

git commit -m "Added another file"
Enter fullscreen mode Exit fullscreen mode

This results in two separate commits for files that logically belong together.

✅ Corrected code:

git add file.txt another_file.txt
git commit -m "Added file.txt and another_file.txt"
Enter fullscreen mode Exit fullscreen mode

Always stage all related changes before committing.

❌ Committing too frequently with small changes:

git add .
git commit -m "Fixed typo"
git add .
git commit -m "Changed color"
git add .
git commit -m "Added comment"
Enter fullscreen mode Exit fullscreen mode

This creates a cluttered history with many small, insignificant commits.

✅ Corrected code:

git add .
git commit -m "Fixed typo, changed color, and added comment"
Enter fullscreen mode Exit fullscreen mode

Group related changes into logical commits.

❌ Forgetting to pull before pushing:

This can lead to conflicts when collaborating with others.

✅ Corrected code:

Before pushing your changes, always run:

git pull origin main # or git pull origin <your_branch_name>

Enter fullscreen mode Exit fullscreen mode

This fetches the latest changes from the remote repository and merges them into your local branch.

Real-World Use Case

Let's say you're building a simple to-do list application. You might start with a basic structure:

# to_do_list.py

def add_task(task):
    print(f"Added task: {task}")

def view_tasks():
    print("No tasks yet!")

if __name__ == "__main__":
    add_task("Buy groceries")
    view_tasks()
Enter fullscreen mode Exit fullscreen mode

Now, you want to add a feature to save tasks to a file. You can create a new branch for this:

git checkout -b save-tasks
Enter fullscreen mode Exit fullscreen mode

Then, you can modify the code to save tasks to a file:

# to_do_list.py

def add_task(task):
    with open("tasks.txt", "a") as f:
        f.write(task + "\n")
    print(f"Added task: {task}")

def view_tasks():
    with open("tasks.txt", "r") as f:
        tasks = f.readlines()
    if tasks:
        for task in tasks:
            print(task.strip())
    else:
        print("No tasks yet!")

if __name__ == "__main__":
    add_task("Buy groceries")
    view_tasks()
Enter fullscreen mode Exit fullscreen mode

Once you're happy with the changes, you can commit them:

git add .
git commit -m "Implemented saving tasks to file"
Enter fullscreen mode Exit fullscreen mode

Finally, you can merge the branch back into the main branch:

git checkout main
git merge save-tasks
Enter fullscreen mode Exit fullscreen mode

Practice Ideas

Here are a few ideas to practice your Git skills:

  1. Create a repository for a simple text-based game: Track your progress as you add features like scoring, levels, and different game modes.
  2. Collaborate with a friend on a project: Use branches and pull requests to work together on the same codebase.
  3. Experiment with reverting commits: Introduce a bug, commit it, and then use git revert to undo the changes.
  4. Practice branching and merging: Create multiple branches for different features and merge them back into the main branch.
  5. Fix a typo in a file and track the change: This will help you understand the basic workflow of staging, committing, and viewing history.

Summary

You've now learned the basics of Git: initializing a repository, staging changes, committing changes, branching, and merging. Git is a powerful tool that will become invaluable as you continue your programming journey. Don't be afraid to experiment and make mistakes – that's how you learn!

Next, you might want to explore more advanced Git concepts like remote repositories (GitHub, GitLab, Bitbucket), pull requests, and resolving merge conflicts. Keep practicing, and you'll be a Git pro in no time!

Top comments (2)

Collapse
 
kamalmost profile image
KamalMostafa
graph LR
    A[Initial Commit] --> B(Branch: New Feature);
    A --> C(Branch: Bug Fix);
    B --> D[Commit on New Feature];
    C --> E[Commit on Bug Fix];
    D --> F{Merge New Feature};
    E --> F;
    F --> G[Final Commit];
Enter fullscreen mode Exit fullscreen mode
graph TD
    A[Initial Commit] --> B(Branch: New Feature);
    A --> C(Branch: Bug Fix);
    B --> D[Commit on New Feature];
    C --> E[Commit on Bug Fix];
    D --> F{Merge New Feature};
    E --> F;
    F --> G[Final Commit];
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kamalmost profile image
KamalMostafa

Seems like Dev.to doesn't resolve **mermaid **correctly.