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.

exit status<br />

return<br />

}<br />

read var_locale<br />

[ -n "$var_locale" ] && eval $1=\$var_locale<br />

# "Lista And": se "var_locale" è presente allora viene impostata<br />

#+ al valore <strong>di</strong> "$1".<br />

echo<br />

while [ "$contai" -le "$ITERAZIONI" ]<br />

do<br />

lettura var<br />

echo "Inserimento nr.$contai = $var"<br />

let "contai += 1"<br />

echo<br />

done<br />

Capitolo 23. Funzioni<br />

# Grazie a Stephane Chazelas per aver fornito questo istruttivo esempio.<br />

exit 0<br />

Exit e Return<br />

Le funzioni restituiscono un valore, chiamato exit status. L’exit status può essere specificato in<br />

maniera esplicita con l’istruzione return, altrimenti corrisponde all’exit status dell’ultimo comando<br />

della funzione (0 in caso <strong>di</strong> successo, un co<strong>di</strong>ce d’errore <strong>di</strong>verso da zero in caso contrario). Questo<br />

exit status può essere usato nello script facendovi riferimento tramite $?. Questo meccanismo<br />

consente alle funzioni <strong>di</strong> avere un “valore <strong>di</strong> ritorno” simile a quello delle funzioni del C.<br />

Termina una funzione. Il comando return 1 può avere opzionalmente come argomento un intero,<br />

che viene restituito allo script chiamante come “exit status” della funzione. Questo exit status viene<br />

assegnato alla variabile $?.<br />

Esempio 23-7. Il maggiore <strong>di</strong> due numeri<br />

#!/bin/bash<br />

# max.sh: Maggiore <strong>di</strong> due numeri.<br />

E_ERR_PARAM=-198 # Se vengono passati meno <strong>di</strong> 2 parametri alla funzione.<br />

UGUALI=-199 # Valore <strong>di</strong> ritorno se i due numeri sono uguali.<br />

# Errore per i valori fuori intervallo passati come parametri alla funzione.<br />

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

{ # Nota: i numeri confrontati devono essere minori <strong>di</strong> 257.<br />

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

451

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

Saved successfully!

Ooh no, something went wrong!