ESC
Commandes 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)

Questions Fréquentes

Git est un système de contrôle de version distribué qui suit les modifications de vos fichiers dans le temps. Il permet à plusieurs développeurs de collaborer sur le même projet sans écraser le travail des autres, conserve un historique complet de chaque modification, vous laisse expérimenter dans des branches sans toucher au code principal et facilite le retour à n'importe quel état précédent. C'est le standard du secteur pour la gestion du code source.

Il existe plusieurs façons selon vos besoins : "git revert HEAD" crée un nouveau commit qui annule le dernier — sûr pour les branches partagées car il préserve l'historique. "git reset --soft HEAD~1" annule le dernier commit mais garde les modifications dans la zone de préparation. "git reset --mixed HEAD~1" (le comportement par défaut) annule le commit et désindexe les modifications, en les conservant dans votre répertoire de travail. "git reset --hard HEAD~1" annule le commit et supprime définitivement toutes les modifications — à utiliser avec précaution. Évitez les resets --hard sur des commits déjà poussés vers un dépôt partagé.

"git merge" combine deux branches en créant un nouveau commit de fusion avec deux commits parents. Cela préserve l'historique complet des deux branches et n'est pas destructif, mais peut alourdir le log de commits de fusion. "git rebase" déplace ou rejoue vos commits sur une autre branche, produisant un historique linéaire et plus propre. Cependant, rebase réécrit l'historique des commits, donc ne rebasez jamais des commits déjà poussés vers une branche distante partagée, cela créerait des problèmes pour les autres contributeurs.

HEAD est un pointeur spécial qui fait référence au commit actuellement extrait — il indique à Git "où vous êtes maintenant" dans l'historique du dépôt. Normalement, HEAD pointe vers le sommet de votre branche actuelle. Lorsque vous changez de branche avec "git checkout", HEAD se déplace vers la nouvelle branche. HEAD~1 désigne le commit précédant HEAD, HEAD~2 deux étapes en arrière, et ainsi de suite. L'état "HEAD détaché" survient quand HEAD pointe directement vers un hash de commit plutôt que vers un nom de branche.

Lorsqu'un conflit de merge se produit, Git suspend la fusion et marque les fichiers en conflit. Ouvrez chaque fichier conflictuel — Git insère des marqueurs indiquant "<<<<<<< HEAD" (vos modifications), "=======" (le séparateur) et ">>>>>>> nom-branche" (les modifications entrantes). Éditez le fichier pour conserver le bon code, en supprimant entièrement les marqueurs de conflit. Ensuite, indexez le fichier résolu avec "git add " et terminez la fusion avec "git commit". Des outils comme VS Code, IntelliJ ou "git mergetool" offrent une interface visuelle pour faciliter la résolution des conflits.