← Git

Commits & Changes

What do `git add` and `git commit` do, and why are they two separate steps?

Show answer — try answering out loud first

git add stages (moves to the staging area) the changes you want to include in the next commit. git commit takes what's in staging and saves it as a permanent snapshot in the history, with a message. They're two steps so you can choose exactly what goes into each commit.

  • git add: you tell Git "I want to include these changes in the next commit." It doesn't save anything to the history yet; it just moves them to the staging area.
  • git commit: takes everything that's in staging and creates a commit: a snapshot of the project with a message, an author, and a date. That commit stays in the history forever.

Having two steps is an advantage: it lets you build clean commits. You can edit five files but commit only two that belong together, and leave the others for another commit with its own message.

The -m flag lets you write the message inline. Without it, Git opens a text editor.

# Stage a specific file
git add index.html

# Stage ALL changes in the working directory
git add .

# Commit what's in staging with a message
git commit -m "Agrega la estructura inicial de la página"
# Output: [main 1a2b3c4] Agrega la estructura inicial de la página
#         1 file changed, 10 insertions(+)

# Shortcut: add + commit ALREADY-tracked files in a single step
git commit -am "Corrige el título del encabezado"
# -a automatically adds changes from already-tracked files
# NOTE: -a does NOT include untracked (new) files

Using git commit -am thinking it includes new files. The -a flag only adds changes from files that Git already tracks; untracked (new) files must be added explicitly with git add. Another classic mistake: running git commit without git add first and being surprised that there's "nothing to commit".

"git add stages the changes I want to include, moving them to the staging area, and git commit saves them as a permanent snapshot in the history with a message. They're two steps on purpose: they let me build clean commits, choosing which files belong together in each commit. I use -m for the message inline, and sometimes commit -am as a shortcut, but keeping in mind that it doesn't include new files."

Quick challenge

You created a new file estilos.css and modified index.html (which was already in Git). You run git commit -am "cambios". What gets saved?

See answer

Only the change to index.html gets saved. The -a flag automatically includes changes from already-tracked files, but estilos.css is new (untracked), so Git ignores it. To include it you'd have to run git add estilos.css before the commit.