Core Git Commands in Detail


Committing Changes

One of the most essential tasks in Git is saving changes to your repository. This is done in two steps:

  • Staging Changes: Use git add to stage your changes. This prepares the changes to be committed.
  • Committing Changes: Use git commit to save the changes to the repository. Each commit should have a meaningful message describing the change.

Example commands:

# Stage a specific file
$ git add filename

# Stage all changes
$ git add .

# Commit changes with a message
$ git commit -m "Add feature X"

A well-written commit message is crucial for understanding the history of your project. Follow these tips:

  • Use the imperative mood (e.g., "Fix bug" instead of "Fixed bug").
  • Keep the summary line short (50 characters or less).
  • Provide additional context in the body if necessary.

Branching Basics

Branches allow you to work on different features or fixes simultaneously without affecting the main codebase.

Basic branch commands:

# List all branches
$ git branch

# Create a new branch
$ git branch new-branch-name

# Switch to a branch
$ git checkout new-branch-name

# Create and switch to a branch in one step (Git 2.23+)
$ git switch -c new-branch-name

Use descriptive branch names to reflect the purpose of the branch, such as feature/login or bugfix/typo-fix.

Merging Branches

When your work on a branch is complete, you can merge it into another branch. This is typically done with git merge.

Steps for merging:

  1. Switch to the branch you want to merge into (e.g., main):
    $ git checkout main
  2. Merge the target branch:
    $ git merge branch-name

If there are conflicts, Git will pause the merge process and indicate the files with conflicts. Resolve these manually, then stage the resolved files and complete the merge:

# Stage resolved files
$ git add resolved-file

# Continue the merge
$ git merge --continue

To avoid frequent conflicts, pull the latest changes from the remote repository before merging:

$ git pull origin main



Post a Comment

0 Comments