0
0
GitHow-ToBeginner · 3 min read

How to Use git commit: Basic Syntax and Examples

Use git commit to save changes to your local Git repository. Run git commit -m "message" to add a commit with a clear message describing your changes.
📐

Syntax

The basic syntax of git commit includes options to add a message and control the commit behavior:

  • git commit -m "message": Adds a commit with a short message describing the changes.
  • git commit -a -m "message": Automatically stages tracked files before committing.
  • git commit --amend: Modifies the last commit.
bash
git commit -m "Your commit message here"
💻

Example

This example shows how to stage a file and commit it with a message:

bash
echo "Hello Git" > example.txt

# Stage the file
 git add example.txt

# Commit with a message
 git commit -m "Add example.txt with greeting message"
Output
[main abc1234] Add example.txt with greeting message 1 file changed, 1 insertion(+) create mode 100644 example.txt
⚠️

Common Pitfalls

Common mistakes when using git commit include:

  • Forgetting to stage files before committing, so no changes are saved.
  • Using vague or empty commit messages, which make history hard to understand.
  • Trying to commit without any changes staged, resulting in an error.

Correct usage requires staging files with git add before committing, and always providing a meaningful message with -m.

bash
git commit -m ""
# Wrong: empty message

git add file.txt
 git commit -m "Add file.txt"
# Right: staged file with message
Output
error: switch `-m' requires a value [main abc1234] Add file.txt 1 file changed, 1 insertion(+)
📊

Quick Reference

CommandDescription
git commit -m "message"Commit staged changes with a message
git commit -a -m "message"Stage tracked files and commit in one step
git commit --amendModify the last commit
git commit --helpShow help for git commit

Key Takeaways

Always stage your changes with git add before committing.
Use git commit -m "message" to save changes with a clear message.
Avoid empty commit messages to keep history understandable.
Use git commit --amend to fix the last commit if needed.
Check git commit --help for more options and details.