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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Capitolo 25. Costrutti lista<br />

lista and<br />

I costrutti “lista and” e “lista or” rappresentano un mezzo per elaborare consecutivamente un elenco <strong>di</strong><br />

coman<strong>di</strong>. I costrutti lista possono sostituire efficacemente complessi enunciati if/then annidati nonché<br />

l’enunciato case.<br />

Concatenare coman<strong>di</strong><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 />

come valore <strong>di</strong> ritorno true (zero). Alla prima restituzione <strong>di</strong> false (non-zero), la serie dei coman<strong>di</strong><br />

termina (il primo comando che ha restituito false è l’ultimo che è stato eseguito).<br />

Esempio 25-1. Usare una “lista and” per verificare gli argomenti da riga <strong>di</strong> comando<br />

#!/bin/bash<br />

# "lista and"<br />

if [ ! -z "$1" ] && echo "Argomento nr.1 = $1" && [ ! -z "$2" ] &&\<br />

echo "Argomento nr.2 = $2"<br />

then<br />

echo "Allo script sono stati passati almeno 2 argomenti."<br />

# Tutti i coman<strong>di</strong> della serie hanno restituito true.<br />

else<br />

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

# Almeno uno dei coman<strong>di</strong> ha restituito false.<br />

fi<br />

# Notate che "if [ ! -z $1 ]" funziona, ma il suo supposto equivalente,<br />

# if [ -n $1 ] no.<br />

# Comunque, l’uso del quoting risolve il problema.<br />

# if [ -n "$1" ] funziona.<br />

# State attenti!<br />

# In una verifica, è sempre meglio usare le variabili con il QUOTING.<br />

# Questo svolge la stesso compito usando solamente enunciati if/then.<br />

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

then<br />

echo "Argomento nr.1 = $1"<br />

fi<br />

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

then<br />

echo "Argomento nr.2 = $2"<br />

echo "Allo script sono stati passati almeno 2 argomenti."<br />

468

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

Saved successfully!

Ooh no, something went wrong!