ESC
Comandos Git

Setup & Config

Command Description Example
git config --global user.name "Name" Set the name attached to all commits globally git config --global user.name "John Doe"
git config --global user.email "email" Set the email attached to all commits globally git config --global user.email "[email protected]"
git config --global core.editor "editor" Set the default text editor for commit messages git config --global core.editor "code --wait"
git config --global color.ui auto Enable helpful colorization of command line output git config --global color.ui auto
git config --list List all configuration settings and their values git config --list --show-origin
git config --global alias.<alias> <command> Create a shorthand alias for a git command git config --global alias.st status
git config --global --unset <key> Remove a specific global config setting git config --global --unset core.editor
git config --global init.defaultBranch main Set the default branch name for new repositories git config --global init.defaultBranch main

Basic Workflow

Command Description Example
git init Initialize a new empty git repository in current directory git init my-project
git clone <url> Clone a remote repository into a new directory git clone https://github.com/user/repo.git
git clone <url> <dir> Clone a repository into a specific directory name git clone https://github.com/user/repo.git my-dir
git status Show the state of the working directory and staging area git status -s (short format)
git add <file> Stage a specific file for the next commit git add index.html
git add . Stage all changes in the current directory git add .
git add -p Interactively stage chunks/hunks of changes git add -p (choose y/n for each hunk)
git commit -m "message" Commit staged changes with an inline commit message git commit -m "feat: add login page"
git commit -am "message" Stage all tracked changes and commit in one step git commit -am "fix: correct typo in header"
git commit --amend Modify the most recent commit (message or content) git commit --amend -m "Updated message"
git diff Show unstaged changes between working tree and index git diff src/app.js
git diff --staged Show staged changes that will go into the next commit git diff --staged
git rm <file> Remove a file from the working tree and staging area git rm obsolete.txt
git mv <old> <new> Move or rename a file, staging the change automatically git mv old-name.txt new-name.txt

Branching

Command Description Example
git branch List all local branches; current branch is marked with * git branch -a (list local and remote branches)
git branch <name> Create a new branch at the current commit git branch feature/login
git checkout <branch> Switch to an existing branch git checkout main
git checkout -b <branch> Create and switch to a new branch in one command git checkout -b feature/signup
git switch <branch> Switch to an existing branch (modern syntax) git switch develop
git switch -c <branch> Create and switch to a new branch (modern syntax) git switch -c feature/dashboard
git branch -d <branch> Delete a merged branch (safe delete) git branch -d feature/login
git branch -D <branch> Force delete a branch regardless of merge status git branch -D old-experiment
git branch -m <old> <new> Rename a branch git branch -m old-name new-name
git merge <branch> Merge a branch into the current branch git merge feature/login
git merge --no-ff <branch> Merge with a merge commit, preserving branch history git merge --no-ff feature/login
git merge --squash <branch> Squash all branch commits into one staged change git merge --squash feature/login
git rebase <branch> Reapply commits on top of another branch git rebase main
git rebase -i HEAD~n Interactively rebase last n commits (squash, reorder, edit) git rebase -i HEAD~3
git cherry-pick <commit> Apply changes from a specific commit onto current branch git cherry-pick a1b2c3d

Remote

Command Description Example
git remote -v List all remote connections with their URLs git remote -v
git remote add <name> <url> Add a new remote connection git remote add origin https://github.com/user/repo.git
git remote remove <name> Remove a remote connection git remote remove origin
git remote rename <old> <new> Rename a remote connection git remote rename origin upstream
git fetch <remote> Download changes from remote without merging git fetch origin
git fetch --all Fetch from all remotes git fetch --all --prune
git pull Fetch and merge changes from the tracking remote branch git pull origin main
git pull --rebase Fetch and rebase instead of merge git pull --rebase origin main
git push <remote> <branch> Push a branch to a remote repository git push origin main
git push -u <remote> <branch> Push and set upstream tracking for the branch git push -u origin feature/login
git push --force-with-lease Force push but fail if remote has unexpected changes (safer than --force) git push --force-with-lease origin feature/login
git push <remote> --delete <branch> Delete a remote branch git push origin --delete old-branch
git push --tags Push all local tags to the remote git push origin --tags

History & Log

Command Description Example
git log Show the commit history for the current branch git log --oneline --graph --decorate
git log --oneline Show compact one-line commit history git log --oneline -10 (last 10 commits)
git log --author="Name" Filter commit history by author name git log --author="John" --oneline
git log --since=<date> Show commits after a specified date git log --since="2024-01-01" --until="2024-12-31"
git log --grep="pattern" Search commit messages matching a pattern git log --grep="fix" --oneline
git log -p <file> Show changes introduced by each commit for a file git log -p src/app.js
git log --follow <file> Follow a file's history across renames git log --follow -p old-name.txt
git show <commit> Show details and diff of a specific commit git show a1b2c3d
git blame <file> Show who last modified each line of a file git blame -L 10,20 src/app.js
git shortlog -sn Show commit count per author, sorted by number git shortlog -sn --all
git diff <branch1>..<branch2> Show changes between two branches git diff main..feature/login
git bisect start Start a binary search for the commit that introduced a bug git bisect start; git bisect bad; git bisect good v1.0

Undo Changes

Command Description Example
git restore <file> Discard changes in working directory (unstaged) git restore index.html
git restore --staged <file> Unstage a file, keeping changes in working directory git restore --staged index.html
git reset HEAD~1 Undo last commit, keeping changes staged git reset HEAD~1 (soft reset by default)
git reset --soft HEAD~n Undo last n commits, keeping all changes staged git reset --soft HEAD~3
git reset --mixed HEAD~n Undo last n commits, unstaging changes (default) git reset HEAD~2
git reset --hard HEAD~n Undo last n commits and discard all changes permanently git reset --hard HEAD~1
git revert <commit> Create a new commit that undoes changes from a commit (safe for shared branches) git revert a1b2c3d
git revert HEAD Create a new commit that reverses the last commit git revert HEAD --no-edit
git stash Save uncommitted changes to a temporary stash git stash push -m "WIP: login feature"
git stash pop Apply the most recent stash and remove it from stash list git stash pop
git stash list List all stashed changesets git stash list
git stash apply stash@{n} Apply a specific stash without removing it git stash apply stash@{2}
git stash drop stash@{n} Remove a specific stash entry git stash drop stash@{0}
git clean -fd Remove untracked files and directories from working tree git clean -fd (use -n first to preview)

Advanced

Command Description Example
git tag <name> Create a lightweight tag at the current commit git tag v1.0.0
git tag -a <name> -m "msg" Create an annotated tag with a message git tag -a v1.0.0 -m "Release version 1.0.0"
git tag -d <name> Delete a local tag git tag -d v1.0.0
git submodule add <url> Add a git repository as a submodule git submodule add https://github.com/user/lib.git lib
git submodule update --init --recursive Initialize and update all submodules git submodule update --init --recursive
git reflog Show a log of all reference changes, useful for recovering lost commits git reflog show HEAD
git worktree add <path> <branch> Check out a branch into a new linked working tree git worktree add ../hotfix-tree hotfix/urgent
git archive --format=zip HEAD > out.zip Create a zip archive of the repository at HEAD git archive --format=tar HEAD | gzip > repo.tar.gz
git gc Run garbage collection to optimize repository performance git gc --aggressive --prune=now
git rev-parse HEAD Get the full SHA of the current HEAD commit git rev-parse --short HEAD (short SHA)

Preguntas Frecuentes

Git es un sistema de control de versiones distribuido que registra los cambios en tus archivos a lo largo del tiempo. Permite que varios desarrolladores trabajen en el mismo proyecto sin sobrescribir el trabajo de los demás, mantiene un historial completo de cada cambio realizado, te deja experimentar en ramas sin afectar el código principal y facilita volver a cualquier estado anterior. Es el estándar del sector para la gestión de código fuente.

Hay varias formas según lo que necesites: "git revert HEAD" crea un nuevo commit que deshace el último — seguro para ramas compartidas ya que conserva el historial. "git reset --soft HEAD~1" deshace el último commit pero mantiene los cambios preparados. "git reset --mixed HEAD~1" (el predeterminado) deshace el commit y desactiva los cambios, manteniéndolos en tu directorio de trabajo. "git reset --hard HEAD~1" deshace el commit y descarta todos los cambios de forma permanente — úsalo con precaución. Evita los resets --hard sobre commits que ya hayas subido a un repositorio compartido.

"git merge" combina dos ramas creando un nuevo commit de fusión con dos commits padre. Esto preserva el historial completo de ambas ramas y es no destructivo, pero puede saturar el log con commits de fusión. "git rebase" mueve o repite tus commits encima de otra rama, produciendo un historial lineal y más limpio. Sin embargo, rebase reescribe el historial de commits, así que nunca hagas rebase de commits que ya hayas subido a una rama remota compartida, ya que causará problemas a otros colaboradores.

HEAD es un puntero especial que apunta al commit actualmente activo — básicamente le dice a Git "dónde estás ahora mismo" en el historial del repositorio. Normalmente, HEAD apunta al último commit de tu rama actual. Cuando cambias de rama con "git checkout", HEAD se mueve a la nueva rama. HEAD~1 se refiere al commit anterior a HEAD, HEAD~2 a dos pasos atrás, y así sucesivamente. El estado "HEAD desasociado" ocurre cuando HEAD apunta directamente a un hash de commit en lugar de a un nombre de rama.

Cuando ocurre un conflicto de merge, Git detiene el proceso y marca los archivos en conflicto. Abre cada archivo conflictivo — Git inserta marcadores mostrando "<<<<<<< HEAD" (tus cambios), "=======" (el divisor) y ">>>>>>> nombre-rama" (los cambios entrantes). Edita el archivo para conservar el código correcto, eliminando por completo los marcadores de conflicto. Luego prepara el archivo resuelto con "git add " y completa el merge con "git commit". Herramientas como VS Code, IntelliJ o "git mergetool" ofrecen una interfaz visual para facilitar la resolución.