Instructions IF

Introduction au scripting Bash

Alex Scriven

Data Scientist

Une instruction IF basique

Une instruction IF basique en Bash a la structure suivante :

if [ CONDITION ]; then

# SOME CODE
else # SOME OTHER CODE
fi

Deux conseils :

  • Espaces entre les crochets et les éléments de la condition (première ligne)
  • Point-virgule après le crochet fermant ];
Introduction au scripting Bash

IF et chaînes de caractères

On peut comparer des chaînes dans une instruction IF :

x="Queen"

if [ $x == "King" ]; then
echo "$x is a King!"
else echo "$x is not a King!" fi
Queen is not a King!

Vous pouvez aussi utiliser != pour « différent de »

Introduction au scripting Bash

IF arithmétiques (option 1)

Les IF arithmétiques peuvent utiliser la structure à doubles parenthèses :

x=10

if (($x > 5)); then echo "$x is more than 5!" fi
10 is more than 5!
Introduction au scripting Bash

IF arithmétiques (option 2)

Les IF arithmétiques peuvent aussi utiliser des crochets et des indicateurs arithmétiques plutôt que (>, <, =, !=, etc.) :

  • -eq pour « égal à »
  • -ne pour « différent de »
  • -lt pour « inférieur à »
  • -le pour « inférieur ou égal à »
  • -gt pour « supérieur à »
  • -ge pour « supérieur ou égal à »
Introduction au scripting Bash

Exemple d'IF arithmétique

Reprenons l'exemple précédent avec la notation à crochets :

x=10
if [ $x -gt 5 ]; then
    echo "$x is more than 5!"
fi
10 is more than 5!
Introduction au scripting Bash

Autres indicateurs conditionnels Bash

Bash propose aussi divers indicateurs liés aux fichiers :

  • -e si le fichier existe
  • -s s'il existe et a une taille > 0
  • -r s'il existe et est lisible
  • -w s'il existe et est inscriptible

Et bien d'autres :

Introduction au scripting Bash

Utiliser ET et OU en Bash

 

Pour combiner des conditions (ET) ou utiliser un OU en Bash, utilisez :

  • && pour ET
  • || pour OU
Introduction au scripting Bash

Conditions multiples

En Bash, vous pouvez chaîner les conditions ainsi :

x=10
if [ $x -gt 5 ] && [ $x -lt 11 ]; then
    echo "$x is more than 5 and less than 11!"
fi

Ou utiliser la notation à doubles crochets :

x=10
if [[ $x -gt 5 && $x -lt 11 ]]; then
    echo "$x is more than 5 and less than 11!"
fi
Introduction au scripting Bash

IF et programmes en ligne de commande

Vous pouvez aussi utiliser de nombreux programmes en ligne de commande directement dans la condition, sans crochets.

Par exemple, si le fichier words.txt contient « Hello World! » :

if grep -q Hello words.txt; then
    echo "Hello is inside!"
fi
Hello is inside!
Introduction au scripting Bash

IF avec sous-shell

Vous pouvez aussi appeler un sous-shell pour votre condition.

Réécrivons le dernier exemple ; le résultat sera identique.

if $(grep -q Hello words.txt); then
    echo "Hello is inside!"
fi
Hello is inside!
Introduction au scripting Bash

Passons à la pratique !

Introduction au scripting Bash

Preparing Video For Download...