Fonctions de base en Bash

Introduction au scripting Bash

Alex Scriven

Data Scientist

Pourquoi des fonctions ?

 

Si vous avez utilisé des fonctions en R ou en Python, vous connaissez ces atouts :

  1. Les fonctions sont réutilisables
  2. Elles permettent un code propre et modulaire
  3. Elles facilitent le partage (il suffit de connaître entrées et sorties)
Introduction au scripting Bash

Anatomie d'une fonction Bash

Décomposons la syntaxe d'une fonction :

  • Commencez par nommer la fonction. Ce nom servira à l'appeler.
    • Choisissez un nom parlant !
  • Ajoutez des parenthèses après le nom
  • Ajoutez le code entre accolades. Vous pouvez y utiliser tout ce vu jusque‑là (boucles, IF, shell‑dans‑le‑shell, etc.) !
  • Optionnel : retourner quelque chose (attention, ce n'est pas ce que vous croyez)

 

Une fonction Bash a la syntaxe suivante :

function_name () {
    #function_code
    return #something
}
Introduction au scripting Bash

Structure alternative d'une fonction Bash

Vous pouvez aussi créer une fonction ainsi :

function function_name {
    #function_code
    return #something
}

Principales différences :

  • Utilisez le mot‑clé function pour indiquer le début de la définition
  • Vous pouvez omettre les parenthèses sur la première ligne, même si beaucoup les gardent par convention
Introduction au scripting Bash

Appeler une fonction Bash

Appeler une fonction Bash consiste simplement à écrire son nom :

function print_hello () {
    echo "Hello world!"
}

print_hello # ici on appelle la fonction
Hello world!
Introduction au scripting Bash

Fonction Bash : Fahrenheit vers Celsius

Écrivons une fonction pour convertir des Fahrenheit en Celsius, comme dans une leçon précédente, avec une variable statique.

temp_f=30

function convert_temp () {
temp_c=$(echo "scale=2; ($temp_f - 32) * 5 / 9" | bc)
echo $temp_c }
convert_temp # appeler la fonction
-1.11
Introduction au scripting Bash

Passons à la pratique !

Introduction au scripting Bash

Preparing Video For Download...