Skip to main content

Conditions


Table of contents

  1. if/elif/else structure
  2. File tests
  3. String tests
  4. Numeric tests
  5. Logical operators
  6. case structure
  7. 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 standardExtended Bash
More portableMore features
Requires escapingNative 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

OperatorDescription
-e fileExists
-f fileIs a regular file
-d fileIs a directory
-r fileIs readable
-w fileIs writable
-x fileIs executable
-s fileSize > 0
-L fileIs a symbolic link
f1 -nt f2f1 newer than f2
f1 -ot f2f1 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

OperatorDescription
-z strEmpty string
-n strNon-empty string
str1 = str2Equality
str1 != str2Inequality
str1 < str2Before (alphabetical)
str1 > str2After (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

OperatorMeaning
-eqEqual
-neNot equal
-ltLess than
-leLess than or equal
-gtGreater than
-geGreater 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 [ ]

OperatorDescription
! exprNOT (negation)
expr1 -a expr2AND
expr1 -o expr2OR
# 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
OperatorDescription
! exprNOT
expr1 && expr2AND
expr1 || expr2OR
# 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, -gt or (( ))
  • Logical operators: &&, ||, !
  • case for multiple choices
  • Always wrap variables in quotes "$var"

🔝 Back to table of contents


← Previous chapter | Next chapter: Loops →