Explorez le monde du Dev, du Cloud et des outils DevOps à travers nos articles et discussionsExplore the world of development, the cloud and DevOps tools
Assurez-vous que vous avez les dernières informations en utilisant git fetch
Ensuite, pour créer une branche locale qui suit une branche distante existante, utilisez :
git branch --set-upstream-to=origin/ma-branche-distante ma-branche-locale
Ensuite, la branche locale "ma-branche-locale" sera configurée pour suivre "origin/ma-branche-distante"
Si vous créez une nouvelle branche locale et que vous voulez activer le suivi lors du premier push, utilisez:
git push --set-upstream origin Cette commande pousse la branche ma-branche-locale vers le dépôt distant et, dans le même temps, configure la branche locale pour suivre la branche nouvellement créée.
Process
Make sure you have the latest information by running git fetch
Next, to create a local branch that tracks an existing remote branch, use:
git branch --set-upstream-to=origin/my-remote-branch my-local-branch
The local branch “my-local-branch” will then be configured to track “origin/my-remote-branch”
If you create a new local branch and want to enable tracking on the first push, use:
git push --set-upstream origin This command pushes the “my-local-branch” branch to the remote repository and, at the same time, configures the local branch to track the newly created branch.
Créer une branche et y basculerCreate and switch to a branch
git switch -C prefix/branch-name
Depuis Git 2.23, 'git switch -c' remplace avantageusement 'checkout -b' pour la clarté et la sécurité.git checkout -b n’est pas supprimé: il reste nécessaire pour d’autres usages (restaurer des fichiers, se positionner sur un commit précis, etc.). git switch ne couvre que la partie “gestion de branches” de git checkout.Voir aussi: git-switch-vs-git-checkoutCreates a new branch and switches to it immediately.git checkout -b is not removed: it is still necessary for other uses (restoring files, positioning yourself on a specific commit, etc.). git switch only covers the “branch management” part of git checkout.See also: git-switch-vs-git-checkout
Lister et compter les branchesListe and count branches
git branch | wc -l
Compte le nombre total de branches locales présentes dans le dépôt Git actuel
Utilisez la commande sans | wc -l pour avoir juste le nom des branches
branches distantes : git branch -r | wc -l (faire un git fetch avant)Locale & Distantes: git branch -a | wc -lgit branch -vv affiche le commit actuel de chaque branche et son suivi distant
Pour utiliser la commande dans un script, préférez: git branch --format='%(refname:short)' pour lister les branches de manière totalement "propre":
sans * devant la branche actuelle,
sans espace vide au début des lignes et sans code couleur invisible qui pourrait perturber un copier-coller ou un script.
Counts the total number of local branches in the current Git repository.
Remote branches: git branch -r | wc -l (run `git fetch` first)Local & Remote: git branch -a | wc -lgit branch -vv displays the current commit for each branch and its remote reference
To use the command in a script, use: git branch --format=“%(refname:short)” to list branches in a completely ‘clean’ format:
without an asterisk before the current branch,
without leading spaces at the start of lines, and without invisible colour coding that could interfere with copy-and-paste or a script.
Nettoyer les branches obsolètes
Clean up obsolete branches
git fetch --prune
La commande met à jour la liste des branches et supprime localement les références des branches distantes qui ont été supprimées sur le serveur.
Utilisez d'abords: git fetch pour mettre à jour la liste locale des branches distantes.
Automatiser le nettoyage avec la commande avec: git config --global fetch.prune trueThis command updates the list of branches and locally removes references to remote branches that have been deleted on the server.
First, use: git fetch to update the local list of remote branches.
Automate the clean-up using the command with:
git config --global fetch.prune true
Renommer une brancheRenaming a branch
git branch -m prefix/new-name
Utilisez cette commande si vous êtes sur la branche (en local)
Si vous êtes sur une autre branche (en local):
git branch -m prefix/old-name prefix/new-name
Si la branche existe déjà sur le dépôt distant. Après le renommage local:
git push origin -u prefix/new-name
Si on souhaite supprimer l'ancien nom distant:
git push origin --delete prefix/old-name
Attention: si cette branche a déjà une Pull Request ouverte, vérifiez qu'elle pointe bien vers le nouveau nom de branche après le renommage.
Use this command if you are on the branch (locally)
If you are on a different branch (locally):
git branch -m prefix/old-name prefix/new-name
If the branch already exists on the remote repository. After renaming it locally:
git push origin -u prefix/new-name
If you wish to delete the old remote branch name:
git push origin --delete prefix/old-name
Please note: if this branch already has an open Pull Request, check that it is pointing to the new branch name after the renaming.
Supprimer une branche distanteDelete a remote branch
git push origin --delete prefix/branch-name
Cette commande supprime définitivement une branche sur le serveur distant
Utilisez, dans l'ordre :
git fetch pour télécharger les dernières modifications, branches et commits depuis le dépôt distant.
git branch -r pour lister toutes les branches distantes.
Une fois la liste obtenue, utilisez la commande de suppression.
Pour un multiligne, ajoutez un [espace]\ backslash à la fin:
git push origin --delete prefix/branchName \
prefix/branchName2 \This command permanently deletes a branch on the remote server
Use the following commands in order:
git fetch to download the latest changes, branches and commits from the remote repository.
git branch -r to list all remote branches.
Once you have the list, use the delete command.
For a multi-line command, add a [space]\ backslash at the end:
git push origin --delete prefix/branchName \
prefix/branchName2 \
Supprimer une branche localeDelete a local branch
git branch -d prefix/branch-name
Cette commande supprime une ou plusieurs branches locale
Utilisez, dans l'ordre : git branch pour lister toutes les branches locale.
Une fois la liste obtenue, utilisez la commande de suppression.
Pour un multiligne, ajoutez un [espace]\ backslash à la fin:
git branch -d prefix/branchName \
prefix/branchName2 \
Utilisez
-D pour forcer la suppression (même si non fusionnée).
This command deletes one or more local branches
Use the following commands in order: git branch to list all local branches.
Once you have the list, use the delete command.
For multiple lines, add a [space]\ backslash at the end:
git branch -d prefix/branchName \
prefix/branchName2 \
Use
-D to force deletion (even if not merged).
Voir fichiers modifiés entre deux branchesShow modified files between branches
git diff branch1..branch2 --name-only
Liste les fichiers modifiés entre deux branches. Utile pour détecter les différences avant une fusion.Shows differences between two branches.
Commit
Appliquer un commit spécifique sur la branche couranteApply a specific commit to the current branch
git cherry-pick <commit-hash>
Permet de copier un commit spécifique situé sur une autre branche et de l'appliquer sur la branche actuelle. C'est l'équivalent d'un "copier-coller" ciblé d'une seule modification.
1. Récupérer le hash du commit sur la branche où se trouve le commit que vous voulez copier et affichez l'historique avec git log --oneline pour copier son identifiant (le hash à 7 ou 40 caractères)
2. Se positionner sur la branchet de destination et executer la commande
git cherry-pick a1b2c3dAllows you to copy a specific commit from another branch and apply it to the current branch. This is the equivalent of a targeted ‘copy and paste’ of a single change.
1. Retrieve the commit hash from the branch containing the commit you wish to copy, and view the history using git log --oneline to copy its identifier (the 7- or 40-character hash)
2. Switch to the destination branch and run the command
git cherry-pick a1b2c3d
Lister les commits (oneline)List commits (oneline)
git log --oneline
Affiche chaque commit sur une seule ligne (SHA court + message)Shows commit history in a compact format.
Modifier le dernier commit sans changer le messageAmend last commit (no message edit)
git commit --amend --no-edit
Réécrit le dernier commit, sans changer son message. Pour corriger les fichiers ajoutés, utilisez la commande sans --no-editModifies the last commit without editing its message.
Réinitialisation dure à un commit spécifiqueHard reset to a specific commit
git reset --hard abc123
Remet tout le repo à l’état du commit abc123Resets repository state to a specific commit.
Réinitialisation dure au commit précédentHard reset to previous commit
git reset --hard HEAD~1
Remet l’état du repo comme si le commit précédent n’avait jamais existé (attention, ceci est destructif)Resets the repository to the previous commit.
Réinitialiser le dernier commitMixed reset last commit
git reset HEAD~1
Annule le commit mais les fichiers modifiés reviennent en "changes not staged for commit"équivaut à git reset --mixed HEAD~1Déplace HEAD et la branche courante au commit précédentL’index est vidé (unstaged), mais le working directory reste intactResets working tree without removing changes.
Réinitialiser le dernier commit softSoft reset last commit
git reset --soft HEAD~1
Annule le dernier commit mais conserve les changements "staged" (prêts à être re-commités)Déplace HEAD et la branche courante au commit précédent.L’index (staging area) et le working directory restent intacts.Restores staging area while keeping file changes.
Revenir à un commit sans perdre les suivantsRevert a commit
git revert abc123
Crée un nouveau commit qui annule les changements du commit abc123, sans toucher à l’historiqueCreates a new commit that reverts a previous one.
Squasher plusieurs commitsSquash multiple commits
git rebase -i HEAD~5
Permet de fusionner plusieurs commits en un unique commit (squash), utile pour nettoyer l’historique avant pushSquashes multiple commits into a single one.
Visualiser les 10 derniers commits graphiquementShow last 10 commits (graph)
git log --oneline --graph -10
Représentation visuelle compacte de l’historique.Displays the latest commits in a visual graph format.
Voir fichiers modifiés entre commitsShow files changed between commits
git diff abc123 def456 --name-only
Affiche uniquement les noms des fichiers modifiés entre deux commits spécifiquesShows file changes between two commits.
Voir le dernier commitShow last commit
git log -1
Montre le dernier commit sur la branche couranteDisplays metadata of the most recent commit.
Voir les commits d’un auteurShow commits by author
git log --author="Alice"
Liste les commits attribués à l’auteur AliceShows all commits made by a specific author.
History
Changer l’auteur de tous les commitsChange commit author
git filter-repo --mailmap new-author.txt
Avant d'exécuter la commande; créer un fichier de correspondance nommé "new-author.txt" à la racine du projet et écrivez la règle de remplacement sous ce format: Nouveau Nom nouvel.email@example.com Ancien Nom ancien.email@example.com
Si vous voulez cibler uniquement par e-mail (sans vérifier le nom), écrivez:
Nouveau Nom nouvel.email@example.com ancien.email@example.comBefore running the command, create a mapping file named ‘new-author.txt’ in the project root directory and enter the replacement rule in the following format: New Name nouvel.email@example.com Old Name ancien.email@example.com
If you want to target by email only (without checking the name), write:
New Name nouvel.email@example.com ancien.email@example.com
Rechercher un mot dans l’historiqueSearch text in commit history
git log -S "keyword"
Cherche tous les commits qui ont ajouté ou retiré le mot ou la chaîne Très utile pour les audits de sécurité ou retrouver une donnée sensible perdue"Pour rechercher une chaîne de caractères ou une expression régulière à l'intérieur des modifications de code et à travers tout l'historique des commits, utilisez: git log -G "regex"Différences: -G vs -S git log -G "regex": Détecte tous les commits où la regex apparaît dans le "diff", même si le nombre total d'occurrences de ce texte dans le fichier reste le mêmegit log -S "string" (le "Pickaxe"): Plus restrictif. Il ne trouve un commit que si le mot recherché a été introduit ou supprimé du fichierSearch for all commits that added or removed the word or string Very useful for security audits or for tracking down lost sensitive data« To search for a string or a regular expression in code changes and across the entire commit history, use: git log -G »regex"Differences: -G vs -S git log -G “regex”: Detects all commits where the regular expression appears in the “diff”, even if the total number of occurrences of that text in the file remains the samegit log -S “string” (the “Pickaxe”): More restrictive. It only finds a commit if the searched-for word has been added to or removed from the file
Retrouver des commits perdus ou supprimésRecover lost commits
git reflog
Affiche l'historique local de tous les déplacements du HEAD, permettant de récupérer un commit ou une branche supprimée par erreur.
Le résultat affiche une liste comme ceci, de la plus récente à la plus ancienne:
a1b2c3d HEAD@{0}: checkout: moving from feature to main
9j8k7l6 HEAD@{2}: commit (amend): Correction du bug d'affichagePour récupérer un commit supprimé:
Option A (Sécurisée) - Créer une nouvelle branche à partir de ce commit : git branch branche-de-sauvetage a1b2c3d
Option B (Directe) - Forcer votre branche actuelle à revenir à cet état avec : git reset --hard a1b2c3dA savoir: Le reflog n'est pas envoyé sur le serveur (GitHub/GitLab). Il ne montre que ce que vous avez fait en local, sur votre ordinateur.
Il n'est pas éternel : Git nettoie automatiquement le reflog après 30 à 90 jours. C'est un outil pour réparer les erreurs récentes.
Displays the local history of all HEAD movements, useful to recover deleted commits or branches.
The result displays a list like this, from most recent to oldest:
a1b2c3d HEAD@{0}: checkout: moving from feature to main
9j8k7l6 HEAD@{2}: commit (amend): Fixed display bugTo recover a deleted commit:
Option A (Safe) – Create a new branch from this commit: git branch rescue-branch a1b2c3d
Option B (Direct) – Force your current branch to revert to this state using: git reset --hard a1b2c3dNote: The reflog is not sent to the server (GitHub/GitLab). It only shows what you have done locally, on your computer.
It is not permanent: Git automatically clears the reflog after 30 to 90 days. It is a tool for rectifying recent errors.
Supprimer un fichier de GitRemoving a file from Git
git rm filename
Cette commande séxécute en général après la suppression du fichier en local. Elle supprime le suivi de Git.
Si vous souhaiter supprimer le fichier de Git MAIS le garder sur votre ordinateur, utilisez:
git rm --cached nom_du_fichier
Dans les deux cas, pour enregistrer définitivement ce changement, vous devez valider la modification avec :
git commit -m "Suppression de fichier"This command is usually run after the file has been deleted locally. It removes the file from Git’s tracking.
If you want to remove the file from Git BUT keep it on your computer, use:
git rm --cached filename
In both cases, to permanently save this change, you must commit the change using:
git commit -m ‘Removing filename’
Supprimer un fichier de l’historiqueRemove file from history
Supprime définitivement le fichier spécifié, de tout l'historique du dépôt Git.
Github repo: git-filter-repo Ou, suivre les étapes décrites sur bfg-repo-cleaner/#usagePermanently deletes the specified file from the entire Git repository history.
GitHub repository: git-filter-repo Alternatively, follow the steps described at bfg-repo-cleaner/#usage
Release
Créer un tag signé pour une releaseCreate a signed release tag
git tag -s v1.0.0 -m "Release version 1.0.0"
Crée un tag immuable et signé cryptographiquement avec GPG pour certifier l'authenticité d'une version en production.Crée un tag immuable et signé cryptographiquement avec GPG pour certifier l'authenticité d'une version en production.
Stash
Appliquer un stash spécifiqueApplying a specific stash
git stash apply "stash^{/stash-name}"
Lister d'abords les stash enregistré avec: git stash list, exécutez ensuite la commande apply
Si le stash à récupérer n'est pas nomé, utilisez:
git stash apply stash@{0}: via son l'identifiant unique
Différence entre apply et pop :
git stash apply "stash^{/stash-name}": applique les modifications et conserve le stash dans la liste.
git stash pop "stash^{/my-stash}": applique les modifications et supprime le stash de la liste.First, list the saved stashes using: git stash list, then run the command apply
If the stash you wish to retrieve is unnamed, use:
git stash apply stash@{0}: using its unique identifier
Difference between `apply` and `pop`:
git stash apply ‘stash^{/stash-name}’: applies the changes and keeps the stash in the list.
git stash pop ‘stash^{/my-stash}’: applies the changes and removes the stash from the list.
Lister les stashsList stashes
git stash list
exemple de résultat: stash@{0}: On main: correction bug affichage formulaire
stash@{1}: On developpement: WIP: developpement page profil
stash@{2}: On main: mon-stashstash@{0} est l'identifiant unique du stash (le plus récent est toujours le {0}).
On main, On ..: est la branche sur laquelle nous étions lorsque l'on à créé le stash.
stash-name ou WIP: ... est le nom (message descriptif) que l'on a donné au stash.Example result: stash@{0}: On main: form display bug fix
stash@{1}: On development: WIP: profile page development
stash@{2}: On main: my-stashstash@{0} is the unique identifier for the stash (the most recent is always {0}).
On main, On ..: is the branch we were on when we created the stash.
stash-name or WIP: ... is the name (descriptive message) given to the stash.
Mettre de côté les modifications sans commiterStash current changes
git stash -u
Permet de sauvegarder temporairement vos modifications non terminées pour retrouver un répertoire de travail propre, avant de les réappliquer plus tard.
L'option -u inclut les nouveaux fichiers non suivis par Git, ce qui évite de les oublier.
Vous pourrez basculer sur une autre branche principale (ex: main ou master), récupérer les nouveautés, puis revenir sur la branche de travail pour y fusionner les mises à jour, par exemple, avant de récupérer le travail mis de côté.
Astuce :
Si vous faites cela souvent, nommez la sauvegarde avec :
git stash push -m "stash-name"Allows you to temporarily save your unfinished changes so that you can return to a clean working directory, before reapplying them later.
The -u option includes new files not tracked by Git, ensuring you don’t forget them.
You can switch to another main branch (e.g. main or master), fetch the latest changes, then return to your working branch to merge the updates, for example, before retrieving the work you’d set aside.
Tip:
If you do this often, name the stash as follows:
git stash push -m ‘stash-name’
Récupérer le dernier stash mis de côtéApply and remove last stash
git stash pop
Restaure les dernières modifications sauvegardées via git stash et les supprime simultanément de la pile des stashes.Restores the most recently stashed changes and removes them from the stash list.
Supprimer tous les stash définitivementPermanently delete all stashes
git stash clear
Attention: cette commande est irréversible. Assurez-vous de ne rien avoir d'important de côté avant de la lancer.Warning: this command cannot be undone. Make sure you haven’t stashed anything important before running it.
Supprimer un stash spécifiqueDeleting a specific stash
git stash drop stash@{1}
Cette commande utilise l'identifiant (ex: stash@{1}) avec la commande drop,
Si vous désirez le supprimer en utilisant son nom, utilisez:
git stash drop "stash^{/my-stash}"This command uses the identifier (e.g. stash@{1}) with the drop command,
If you want to delete it by name, use:
git stash drop ‘stash^{/my-stash}’