11.04.2013 Views

Guida avanzata di scripting Bash - Portale Posta DMI

Guida avanzata di scripting Bash - Portale Posta DMI

Guida avanzata di scripting Bash - Portale Posta DMI

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Capitolo 23. Funzioni<br />

# ^^^^^^ Nessun parametro passato avrà mai un valore simile.<br />

max2 () # "Restituisce" il maggiore <strong>di</strong> due numeri.<br />

{<br />

if [ -z "$2" ]<br />

then<br />

echo $E_ERR_PARAM<br />

return<br />

fi<br />

if [ "$1" -eq "$2" ]<br />

then<br />

echo $UGUALI<br />

return<br />

else<br />

if [ "$1" -gt "$2" ]<br />

then<br />

valritorno=$1<br />

else<br />

valritorno=$2<br />

fi<br />

fi<br />

echo $valritorno # Visualizza (allo stdout) il valore invece <strong>di</strong> restituirlo.<br />

# Perché?<br />

}<br />

val_ritorno=$(max2 33001 33997)<br />

# ^^^^ Nome della funzione<br />

# ^^^^^ ^^^^^ Parametri passati<br />

# Si tratta, in realtà, <strong>di</strong> una forma <strong>di</strong> sostituzione <strong>di</strong> comando:<br />

#+ che tratta una funzione come se fosse un comando<br />

#+ e che assegna lo stdout della funzione alla variabile "val_ritorno".<br />

# =============================== RISULTATO ==============================<br />

if [ "$val_ritorno" -eq "$E_ERR_PARAM" ]<br />

then<br />

echo "Errore nel numero <strong>di</strong> parametri passati alla funzione <strong>di</strong> confronto!"<br />

elif [ "$val_ritorno" -eq "$UGUALI" ]<br />

then<br />

echo "I due numeri sono uguali."<br />

else<br />

echo "Il maggiore dei due numeri è $val_ritorno."<br />

fi<br />

# ========================================================================<br />

exit 0<br />

# Esercizi:<br />

# --------<br />

# 1) Trovate un modo più elegante per verificare<br />

#+ il numero <strong>di</strong> parametri passati alla funzione.<br />

# 2) Semplificate la struttura if/then presente nel blocco "RISULTATO."<br />

# 3) Riscrivete lo script in modo che l’input sia dato dai parametri passati<br />

#+ da riga <strong>di</strong> comando.<br />

456

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!