Conditions
Table of contents
- if/elif/else structure
- File tests
- String tests
- Numeric tests
- Logical operators
- case structure
- Practical exercises
1 - if/elif/else structure
Basic syntax
if [ condition ]; then
# commandes si vrai
fi
# Avec else
if [ condition ]; then
# commandes si vrai
else
# commandes si faux
fi
# Avec elif
if [ condition1 ]; then
# si condition1 vraie
elif [ condition2 ]; then
# si condition2 vraie
else
# sinon
fi
Test with [ ] vs [[ ]]
[ ] | [[ ]] |
|---|---|
| POSIX standard | Extended Bash |
| More portable | More features |
| Requires escaping | Native pattern matching |
# [ ] standard
if [ "$var" = "test" ]; then
echo "ok"
fi
# [[ ]] étendu (recommandé en Bash)
if [[ $var == "test" ]]; then
echo "ok"
fi
# Pattern matching (seulement avec [[ ]])
if [[ $fichier == *.txt ]]; then
echo "Fichier texte"
fi
Test with a command
# Le code de retour détermine vrai/faux
if grep -q "error" /var/log/syslog; then
echo "Erreurs trouvées"
fi
# Commande directe
if ping -c 1 google.com > /dev/null 2>&1; then
echo "Internet OK"
else
echo "Pas de connexion"
fi
🔝 Back to table of contents
2 - File tests
Test operators
| Operator | Description |
|---|---|
-e file | Exists |
-f file | Is a regular file |
-d file | Is a directory |
-r file | Is readable |
-w file | Is writable |
-x file | Is executable |
-s file | Size > 0 |
-L file | Is a symbolic link |
f1 -nt f2 | f1 newer than f2 |
f1 -ot f2 | f1 older than f2 |
Examples
#!/bin/bash
file="/etc/passwd"
# Vérifier l'existence
if [ -e "$file" ]; then
echo "$file existe"
fi
# Vérifier si c'est un fichier
if [ -f "$file" ]; then
echo "$file est un fichier"
fi
# Vérifier si lisible
if [ -r "$file" ]; then
echo "$file est lisible"
fi
# Vérifier si un répertoire existe
if [ -d "/var/log" ]; then
echo "/var/log est un répertoire"
fi
# Combiné
if [ -f "$file" ] && [ -r "$file" ]; then
echo "$file est un fichier lisible"
fi
Practical script
#!/bin/bash
# Vérifier un fichier de configuration
CONFIG_FILE="${1:-/etc/myapp.conf}"
if [ ! -e "$CONFIG_FILE" ]; then
echo "Erreur: $CONFIG_FILE n'existe pas"
exit 1
fi
if [ ! -f "$CONFIG_FILE" ]; then
echo "Erreur: $CONFIG_FILE n'est pas un fichier"
exit 1
fi
if [ ! -r "$CONFIG_FILE" ]; then
echo "Erreur: $CONFIG_FILE n'est pas lisible"
exit 1
fi
echo "Configuration OK: $CONFIG_FILE"
🔝 Back to table of contents
3 - String tests
Operators
| Operator | Description |
|---|---|
-z str | Empty string |
-n str | Non-empty string |
str1 = str2 | Equality |
str1 != str2 | Inequality |
str1 < str2 | Before (alphabetical) |
str1 > str2 | After (alphabetical) |
Examples
nom="Alice"
vide=""
# Chaîne vide
if [ -z "$vide" ]; then
echo "La variable est vide"
fi
# Chaîne non vide
if [ -n "$nom" ]; then
echo "La variable contient: $nom"
fi
# Égalité
if [ "$nom" = "Alice" ]; then
echo "Bonjour Alice"
fi
# Avec [[ ]] (recommandé)
if [[ $nom == "Alice" ]]; then
echo "Bonjour Alice"
fi
Pattern matching (with [[ ]])
email="[email protected]"
# Pattern avec *
if [[ $email == *@*.* ]]; then
echo "Format email valide"
fi
# Pattern avec ?
if [[ $fichier == ???.txt ]]; then
echo "Fichier de 3 caractères .txt"
fi
# Regex avec =~
if [[ $email =~ ^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]+$ ]]; then
echo "Email valide (regex)"
fi
Important
Always wrap variables in quotes inside [ ] to avoid errors with empty strings or strings containing spaces.
🔝 Back to table of contents
4 - Numeric tests
Comparison operators
| Operator | Meaning |
|---|---|
-eq | Equal |
-ne | Not equal |
-lt | Less than |
-le | Less than or equal |
-gt | Greater than |
-ge | Greater than or equal |
Examples
age=25
if [ $age -ge 18 ]; then
echo "Majeur"
else
echo "Mineur"
fi
# Avec [[ ]] ou (( ))
if [[ $age -ge 18 ]]; then
echo "Majeur"
fi
# Arithmétique avec (( )) - syntaxe C
if (( age >= 18 )); then
echo "Majeur"
fi
if (( age > 20 && age < 30 )); then
echo "Entre 20 et 30 ans"
fi
Arithmetic operators inside (( ))
a=10
b=3
if (( a > b )); then echo "a > b"; fi
if (( a == 10 )); then echo "a == 10"; fi
if (( a % 2 == 0 )); then echo "a est pair"; fi
if (( a >= 5 && a <= 15 )); then echo "a entre 5 et 15"; fi
🔝 Back to table of contents
5 - Logical operators
Inside [ ]
| Operator | Description |
|---|---|
! expr | NOT (negation) |
expr1 -a expr2 | AND |
expr1 -o expr2 | OR |
# Négation
if [ ! -f "/tmp/lock" ]; then
echo "Pas de fichier lock"
fi
# ET
if [ -f "$file" -a -r "$file" ]; then
echo "Fichier existe et lisible"
fi
# OU
if [ -z "$var" -o "$var" = "default" ]; then
var="default"
fi
Inside [[ ]] (recommended)
| Operator | Description |
|---|---|
! expr | NOT |
expr1 && expr2 | AND |
expr1 || expr2 | OR |
# Plus lisible avec [[ ]]
if [[ -f "$file" && -r "$file" ]]; then
echo "Fichier existe et lisible"
fi
if [[ -z "$var" || "$var" == "default" ]]; then
var="default"
fi
# Combinaison complexe
if [[ ( $a -gt 5 && $b -lt 10 ) || $c -eq 0 ]]; then
echo "Condition complexe vraie"
fi
Operators outside tests
# && : exécute si succès
mkdir /tmp/test && echo "Répertoire créé"
# || : exécute si échec
cd /nonexistent || echo "Échec du cd"
# Combinaison courante
command && echo "OK" || echo "FAIL"
🔝 Back to table of contents
6 - case structure
Syntax
case $variable in
pattern1)
# commandes
;;
pattern2|pattern3)
# commandes pour pattern2 OU pattern3
;;
*)
# défaut (comme else)
;;
esac
Example: Menu
#!/bin/bash
echo "1. Afficher la date"
echo "2. Afficher l'utilisateur"
echo "3. Quitter"
read -p "Choix: " choix
case $choix in
1)
date
;;
2)
echo "Utilisateur: $USER"
;;
3)
echo "Au revoir!"
exit 0
;;
*)
echo "Choix invalide"
exit 1
;;
esac
Advanced patterns
#!/bin/bash
fichier="$1"
case $fichier in
*.txt)
echo "Fichier texte"
;;
*.jpg|*.png|*.gif)
echo "Image"
;;
*.sh)
echo "Script shell"
;;
[0-9]*)
echo "Commence par un chiffre"
;;
*)
echo "Type inconnu"
;;
esac
Option processing
#!/bin/bash
while [[ $# -gt 0 ]]; do
case $1 in
-v|--verbose)
VERBOSE=true
shift
;;
-f|--file)
FILE="$2"
shift 2
;;
-h|--help)
echo "Usage: $0 [-v] [-f file]"
exit 0
;;
*)
echo "Option inconnue: $1"
exit 1
;;
esac
done
🔝 Back to table of contents
7 - Practical exercises
Exercise 1: Age check
# Script qui demande l'âge et affiche:
# - "Mineur" si < 18
# - "Majeur" si >= 18 et < 65
# - "Senior" si >= 65
Solution
#!/bin/bash
read -p "Entrez votre âge: " age
if (( age < 18 )); then
echo "Mineur"
elif (( age < 65 )); then
echo "Majeur"
else
echo "Senior"
fi
Exercise 2: File type
# Script qui prend un chemin en argument et affiche:
# - "Fichier" si c'est un fichier
# - "Répertoire" si c'est un répertoire
# - "Lien" si c'est un lien symbolique
# - "N'existe pas" sinon
Solution
#!/bin/bash
path="${1:?Usage: $0 <path>}"
if [ -L "$path" ]; then
echo "Lien symbolique"
elif [ -f "$path" ]; then
echo "Fichier"
elif [ -d "$path" ]; then
echo "Répertoire"
else
echo "N'existe pas"
fi
Quiz
Q1. What is the difference between [ ] and [[ ]]?
Answer
[ ] is POSIX standard, [[ ]] is Bash-specific with more features (pattern matching, regex, no escaping needed).
Q2. How do you test whether a file exists and is readable?
Answer
if [[ -f "$file" && -r "$file" ]]; then ...
Q3. How do you compare two numbers in Bash?
Answer
With -eq, -ne, -lt, -le, -gt, -ge or with (( )) for arithmetic syntax.
🔝 Back to table of contents
Key takeaways
[[ ]]>[ ]in Bash (more features)- File tests:
-e,-f,-d,-r,-w,-x - String tests:
-z,-n,=,!= - Numeric tests:
-eq,-ne,-lt,-gtor(( )) - Logical operators:
&&,||,! casefor multiple choices- Always wrap variables in quotes
"$var"