Functions
Table of contents
- Defining functions
- Arguments and parameters
- Return values
- Local variables and scope
- Advanced functions
- Practical exercises
1 - Defining functions
Syntax
# Méthode 1 (recommandée)
nom_fonction() {
# commandes
}
# Méthode 2 (avec mot-clé function)
function nom_fonction {
# commandes
}
# Méthode 3 (combinée)
function nom_fonction() {
# commandes
}
Simple example
#!/bin/bash
# Définir la fonction
dire_bonjour() {
echo "Bonjour, monde!"
}
# Appeler la fonction
dire_bonjour
Function with logic
#!/bin/bash
afficher_date() {
echo "=== Date actuelle ==="
date '+%Y-%m-%d %H:%M:%S'
echo "===================="
}
# Utilisation
afficher_date
Definition order
#!/bin/bash
# ERREUR: fonction appelée avant définition
ma_fonction # bash: ma_fonction: command not found
ma_fonction() {
echo "Hello"
}
# CORRECT: définir avant d'appeler
ma_fonction() {
echo "Hello"
}
ma_fonction # Fonctionne
🔝 Back to table of contents
2 - Arguments and parameters
Passing arguments
saluer() {
echo "Bonjour, $1!"
}
saluer "Alice" # Bonjour, Alice!
saluer "Bob" # Bonjour, Bob!
Argument variables
| Variable | Description |
|---|---|
$1, $2... | Positional arguments |
$# | Number of arguments |
$@ | All arguments (separate) |
$* | All arguments (single string) |
$0 | Script name (not the function) |
Complete example
afficher_info() {
echo "Fonction appelée avec $# arguments"
echo "Argument 1: $1"
echo "Argument 2: $2"
echo "Tous: $@"
}
afficher_info "hello" "world" "!"
# Fonction appelée avec 3 arguments
# Argument 1: hello
# Argument 2: world
# Tous: hello world !
Arguments with default values
creer_utilisateur() {
local nom="${1:-guest}"
local home="${2:-/home/$nom}"
local shell="${3:-/bin/bash}"
echo "Création: $nom"
echo " Home: $home"
echo " Shell: $shell"
}
creer_utilisateur # Valeurs par défaut
creer_utilisateur "alice" # Nom personnalisé
creer_utilisateur "bob" "/opt/bob" # Nom et home
Validating arguments
diviser() {
if [ $# -ne 2 ]; then
echo "Usage: diviser <dividende> <diviseur>" >&2
return 1
fi
if [ "$2" -eq 0 ]; then
echo "Erreur: division par zéro" >&2
return 1
fi
echo $(( $1 / $2 ))
}
diviser 10 2 # 5
diviser 10 0 # Erreur
diviser 10 # Usage
🔝 Back to table of contents
3 - Return values
Return code with return
est_pair() {
if (( $1 % 2 == 0 )); then
return 0 # Succès (vrai en shell)
else
return 1 # Échec (faux en shell)
fi
}
if est_pair 4; then
echo "4 est pair"
fi
if ! est_pair 3; then
echo "3 est impair"
fi
Conventional return codes
| Code | Meaning |
|---|---|
0 | Success |
1 | General error |
2 | Misuse |
126 | Permission denied |
127 | Command not found |
Returning a value via stdout
calculer_somme() {
local somme=0
for n in "$@"; do
((somme += n))
done
echo $somme # "Retourne" via stdout
}
# Capturer le résultat
resultat=$(calculer_somme 1 2 3 4 5)
echo "Somme: $resultat" # Somme: 15
Combining return code and value
chercher_fichier() {
local pattern="$1"
local dir="${2:-.}"
local result=$(find "$dir" -name "$pattern" -type f 2>/dev/null | head -1)
if [ -n "$result" ]; then
echo "$result" # Valeur via stdout
return 0 # Succès
else
return 1 # Échec
fi
}
# Utilisation
if fichier=$(chercher_fichier "*.conf" /etc); then
echo "Trouvé: $fichier"
else
echo "Non trouvé"
fi
🔝 Back to table of contents
4 - Local variables and scope
Global vs local variables
#!/bin/bash
global_var="Je suis globale"
ma_fonction() {
local local_var="Je suis locale"
global_var="Modifiée dans la fonction"
echo "Dans fonction: $global_var"
echo "Dans fonction: $local_var"
}
ma_fonction
echo "Après fonction: $global_var" # Modifiée
echo "Après fonction: $local_var" # (vide)
The local keyword
compteur() {
local count=0 # Variable locale
for i in {1..5}; do
((count++))
done
echo $count
}
count=100
resultat=$(compteur)
echo "Résultat: $resultat" # 5
echo "Count global: $count" # 100 (non modifié)
Best practices
#!/bin/bash
# BONNE PRATIQUE: toujours utiliser local
traiter_fichier() {
local fichier="$1"
local contenu
local ligne
contenu=$(cat "$fichier")
# ...
}
# MAUVAISE PRATIQUE: variables globales implicites
traiter_fichier_mauvais() {
fichier="$1" # Pollue l'espace global
contenu=$(cat "$fichier")
}
🔝 Back to table of contents
5 - Advanced functions
Recursion
factorielle() {
local n=$1
if (( n <= 1 )); then
echo 1
else
local prev=$(factorielle $((n - 1)))
echo $((n * prev))
fi
}
echo "5! = $(factorielle 5)" # 120
Functions in files
# lib/utils.sh
log_info() {
echo "[INFO] $(date '+%H:%M:%S') $*"
}
log_error() {
echo "[ERROR] $(date '+%H:%M:%S') $*" >&2
}
die() {
log_error "$@"
exit 1
}
# main.sh
#!/bin/bash
source lib/utils.sh
log_info "Démarrage du script"
# ...