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.

Esempio 25-3. Utilizzare la “lista or” in combinazione con una “lista and”<br />

#!/bin/bash<br />

Capitolo 25. Costrutti lista<br />

# delete.sh, utility <strong>di</strong> cancellazione <strong>di</strong> file non molto intelligente.<br />

# Utilizzo: delete nomefile<br />

E_ERR_ARG=65<br />

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

then<br />

echo "Utilizzo: ‘basename $0‘ nomefile"<br />

exit $E_ERR_ARG # Nessun argomento? Abbandono.<br />

else<br />

file=$1 # Imposta il nome del file.<br />

fi<br />

[ ! -f "$file" ] && echo "File \"$file\" non trovato. \<br />

Mi rifiuto, in modo vile, <strong>di</strong> cancellare un file inesistente."<br />

# LISTA AND, fornisce il messaggio d’errore se il file non è presente.<br />

# Notate il messaggio <strong>di</strong> echo che continua alla riga successiva per mezzo del<br />

#+ carattere <strong>di</strong> escape.<br />

[ ! -f "$file" ] || (rm -f $file; echo "File \"$file\" cancellato.")<br />

# LISTA OR, per cancellare il file se presente.<br />

# Notate l’inversione logica precedente.<br />

# La LISTA AND viene eseguita se il risultato è true, la LISTA OR se è false.<br />

exit 0<br />

Cautela<br />

Se il primo comando <strong>di</strong> una “lista or” restituisce true, esso verrà eseguito<br />

comunque .<br />

# ==> Questi frammenti <strong>di</strong> co<strong>di</strong>ce, presi dallo script/etc/rc.d/init.d/single<br />

#+==> <strong>di</strong> Miquel van Smoorenburg, illustrano l’impiego delle liste "and" e "or".<br />

# ==> I commenti con la "freccia" sono stati aggiunti dall’autore del libro.<br />

[ -x /usr/bin/clear ] && /usr/bin/clear<br />

# ==> Se /usr/bin/clear esiste, allora viene invocato.<br />

# ==> Verificare l’esistenza <strong>di</strong> un comando prima che venga eseguito<br />

#+==> evita messaggi d’errore e i conseguenti avvertimenti.<br />

# ==> . . .<br />

470

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

Saved successfully!

Ooh no, something went wrong!