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.

lista or<br />

else<br />

echo "Allo script sono stati passati meno <strong>di</strong> 2 argomenti."<br />

fi<br />

# È più lungo e meno elegante <strong>di</strong> una "lista and".<br />

exit 0<br />

Capitolo 25. Costrutti lista<br />

Esempio 25-2. Un’altra verifica <strong>di</strong> argomenti da riga <strong>di</strong> comando utilizzando una “lista and”<br />

#!/bin/bash<br />

ARG=1 # Numero degli argomenti attesi.<br />

E_ERR_ARG=65 # Valore d’uscita se il numero <strong>di</strong> argomenti passati è errato.<br />

test $# -ne $ARG && echo "Utilizzo: ‘basename $0‘ $ARG \<br />

argomento/i" && exit $E_ERR_ARG<br />

# Se la prima con<strong>di</strong>zione dà come risultato vero (numero errato <strong>di</strong> argomenti<br />

#+ passati allo script), allora vengono eseguiti i coman<strong>di</strong> successivi<br />

#+ e lo script termina.<br />

# La riga seguente verrà eseguita solo se fallisce la verifica precedente.<br />

echo "Allo script è stato passato un numero corretto <strong>di</strong> argomenti."<br />

exit 0<br />

# Per verificare il valore d’uscita, eseguite "echo $?" dopo che lo script<br />

#+ è terminato.<br />

Naturalmente, una lista and può anche essere usata per impostare le variabili ad un valore<br />

predefinito.<br />

arg1=$@ # Imposta $arg1 al numero <strong>di</strong> argomenti passati da riga <strong>di</strong><br />

#+ comando, se ce ne sono.<br />

[ -z "$arg1" ] && arg1=DEFAULT<br />

# Viene impostata a DEFAULT se, da riga <strong>di</strong> comando, non è<br />

#+ stato passato niente.<br />

comando-1 || comando-2 || comando-3 || ... comando-n<br />

Ogni comando che a turno deve essere eseguito si accerta che quello precedente abbia restituito<br />

false. Alla prima restituzione <strong>di</strong> true, la serie dei coman<strong>di</strong> termina (il primo comando che ha<br />

restituito true è l’ultimo che è stato eseguito). Ovviamente è l’inverso della “lista and”.<br />

469

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

Saved successfully!

Ooh no, something went wrong!