Essential Git Commands
Master the basic commands for tracking changes, creating commits, and managing your files.
Essential Git Commands
Now that Git is installed and configured, let’s explore the commands you’ll use every day. This tutorial covers the fundamental operations for managing your files and building a coherent history of your project.
Git Workflow Overview
Status and Information Commands
git status
The most commonly used command for checking the state of your repository:
# Voir l'état complet
git status
# Version courte
git status -s
git status --short
Example output:
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: index.html
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: README.md
Untracked files:
(use "git add <file>..." to include in what will be committed)
style.css
git log
View the commit history:
# Historique complet
git log
# Version condensée
git log --oneline
# Avec graphique des branches
git log --oneline --graph --all
# Limiter le nombre de commits
git log -5
# Depuis une date
git log --since="2024-01-01"
# Par auteur
git log --author="Nom Auteur"
git show
Display the details of a commit:
# Dernier commit
git show
# Commit spécifique
git show abc1234
# Fichier spécifique dans un commit
git show abc1234:fichier.txt
File Management
git add
Add files to the staging area:
# Ajouter un fichier spécifique
git add fichier.txt
# Ajouter plusieurs fichiers
git add fichier1.txt fichier2.txt
# Ajouter tous les fichiers modifiés
git add .
# Ajouter tous les fichiers (même supprimés)
git add -A
git add --all
# Ajouter interactivement
git add -i
# Ajouter par parties (patch)
git add -p
git commit
Create a snapshot of your changes:
# Commit avec message
git commit -m "Message de commit"
# Commit avec message détaillé
git commit -m "Titre du commit" -m "Description détaillée"
# Commit en ajoutant automatiquement les fichiers modifiés
git commit -am "Message de commit"
# Modifier le dernier commit
git commit --amend
# Commit avec signature GPG
git commit -S -m "Message signé"
Best Practices for Commit Messages
# Format recommandé
git commit -m "type: description courte
Description plus détaillée si nécessaire.
- Point important 1
- Point important 2
Fixes #123"
Common types:
feat:new featurefix:bug fixdocs:documentationstyle:formatting, missing semicolons, etc.refactor:code refactoringtest:adding testschore:maintenance
Managing Changes
git diff
Compare changes:
# Différences dans le working directory
git diff
# Différences dans la staging area
git diff --staged
git diff --cached
# Différences entre deux commits
git diff abc1234 def5678
# Différences d'un fichier spécifique
git diff fichier.txt
# Statistiques des modifications
git diff --stat
git restore
Undo changes (Git 2.23+):
# Restaurer un fichier modifié
git restore fichier.txt
# Restaurer tous les fichiers modifiés
git restore .
# Retirer un fichier de la staging area
git restore --staged fichier.txt
# Restaurer depuis un commit spécifique
git restore --source=abc1234 fichier.txt
git reset
Reset the state of the repository:
# Retirer un fichier de la staging area
git reset fichier.txt
# Réinitialiser la staging area
git reset
# Réinitialiser au commit précédent (garde les modifications)
git reset HEAD~1
# Réinitialiser complètement (ATTENTION : perte de données)
git reset --hard HEAD~1
Managing Files and Folders
git rm
Delete files:
# Supprimer un fichier du dépôt et du système
git rm fichier.txt
# Supprimer seulement du dépôt (garder localement)
git rm --cached fichier.txt
# Supprimer un dossier récursivement
git rm -r dossier/
git mv
Move or rename files:
# Renommer un fichier
git mv ancien-nom.txt nouveau-nom.txt
# Déplacer un fichier
git mv fichier.txt dossier/fichier.txt
The .gitignore File
Ignore files and folders:
# Fichiers de log
*.log
# Dossiers de build
build/
dist/
# Fichiers de configuration locale
.env
config.local.js
# Dépendances
node_modules/
vendor/
# Fichiers système
.DS_Store
Thumbs.db
# IDE
.vscode/
.idea/
*.swp
*.swo
# Fichiers temporaires
*.tmp
*.temp
.gitignore Commands
# Vérifier si un fichier est ignoré
git check-ignore fichier.txt
# Forcer l'ajout d'un fichier ignoré
git add -f fichier.txt
# Retirer un fichier déjà tracké mais maintenant ignoré
git rm --cached fichier.txt
Navigating the History
git checkout
Navigate between commits and branches:
# Aller à un commit spécifique (mode détaché)
git checkout abc1234
# Revenir à la branche principale
git checkout main
# Créer et basculer vers une nouvelle branche
git checkout -b nouvelle-branche
git switch (Git 2.23+)
A modern alternative to checkout:
# Basculer vers une branche
git switch main
# Créer et basculer vers une nouvelle branche
git switch -c nouvelle-branche
# Revenir à la branche précédente
git switch -
Help and Information Commands
git help
Get help:
# Aide générale
git help
# Aide pour une commande spécifique
git help commit
git commit --help
# Liste des commandes courantes
git help -a
git config
Manage configuration:
# Voir toute la configuration
git config --list
# Voir une valeur spécifique
git config user.name
# Modifier une valeur
git config --global user.email "nouveau@email.com"
Practice Exercises
Exercise 1: Basic Workflow
# 1. Créer un nouveau projet
mkdir exercice-git
cd exercice-git
git init
# 2. Créer des fichiers
echo "# Mon Projet" > README.md
echo "console.log('Hello World');" > app.js
echo "body { margin: 0; }" > style.css
# 3. Vérifier le statut
git status
# 4. Ajouter les fichiers
git add README.md app.js
git status
# 5. Faire un commit
git commit -m "feat: ajout des fichiers de base"
# 6. Ajouter le CSS
git add style.css
git commit -m "style: ajout du CSS de base"
# 7. Voir l'historique
git log --oneline
Exercise 2: Changes and Fixes
# 1. Modifier un fichier
echo "// Commentaire ajouté" >> app.js
# 2. Voir les différences
git diff
# 3. Ajouter à la staging area
git add app.js
# 4. Voir les différences staged
git diff --staged
# 5. Commit
git commit -m "docs: ajout de commentaire"
# 6. Modifier le dernier commit
git commit --amend -m "docs: ajout de commentaire dans app.js"
Exercise 3: Handling Mistakes
# 1. Créer un fichier par erreur
echo "Fichier temporaire" > temp.txt
git add temp.txt
# 2. Retirer de la staging area
git restore --staged temp.txt
# 3. Supprimer le fichier
rm temp.txt
# 4. Modifier un fichier puis l'annuler
echo "Modification non désirée" >> README.md
git restore README.md
Useful Advanced Commands
git stash
Temporarily save changes:
# Sauvegarder les modifications
git stash
# Sauvegarder avec un message
git stash push -m "Travail en cours sur la feature X"
# Voir la liste des stash
git stash list
# Appliquer le dernier stash
git stash pop
# Appliquer un stash spécifique
git stash apply stash@{1}
git clean
Clean up untracked files:
# Voir ce qui serait supprimé
git clean -n
# Supprimer les fichiers non trackés
git clean -f
# Supprimer aussi les dossiers
git clean -fd
Useful Aliases
Set up these aliases to save time:
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.unstage 'restore --staged'
git config --global alias.last 'log -1 HEAD'
git config --global alias.lg 'log --oneline --graph --decorate --all'
git config --global alias.amend 'commit --amend --no-edit'
Common Troubleshooting
Undo the last commit (keeping your changes)
git reset HEAD~1
Completely undo the last commit
git reset --hard HEAD~1
Recover a deleted file
git restore fichier.txt
# ou depuis un commit spécifique
git restore --source=HEAD~1 fichier.txt
See who modified a line
git blame fichier.txt
Best Practices
- Commit often: Make small, frequent commits
- Write clear messages: Describe what the commit does
- Check before committing:
git statusandgit diff - Use .gitignore: Avoid tracking unnecessary files
- Test before committing: Make sure the code works
Additional Resources
Cheat sheets
Visual tools
gitk: Built-in graphical interfacegit gui: Interface for commits
Conclusion
These commands form the foundation of your day-to-day Git usage. Mastering these operations will let you manage your projects efficiently and maintain a clean, coherent history.
In the next tutorial, we’ll explore branches and merging, essential concepts for collaborative work and managing parallel features.
Estimated reading time: 25 minutes
Level: Beginner
Previous step: Configuration and First Steps
Next step: Branches and Merging