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 33. Miscellanea<br />

• Eseguire uno script su una macchina sulla quale non è installato il comando su cui lo script si basa, è<br />

pericoloso. Si usi whatis per evitare potenziali problemi.<br />

CMD=comando1 # Scelta primaria.<br />

PianoB=comando2 # Comando <strong>di</strong> ripiego.<br />

verifica_comando=$(whatis "$CMD" | grep ’nothing appropriate’) #*<br />

# Se ’comando1’ non viene trovato sul sistema , ’whatis’ restituisce<br />

#+ "comando1: nothing appropriate."<br />

#<br />

# Un’alternativa più sicura sarebbe:<br />

# verifica_comando=$(whereis "$CMD" | grep \/)<br />

# Ma allora il senso della verifica seguente andrebbe invertito,<br />

#+ dal momento che la variabile $verifica_comando è impostata solo se<br />

#+ $CMD è presente sul sistema.<br />

# (Grazie, bojster.)<br />

if [[ -z "$verifica_comando" ]] # Verifica se il comando è presente.<br />

then<br />

$CMD opzione1 opzione2 # Esegue comando1 con le opzioni.<br />

else # Altrimenti,<br />

$PianoB #+ esegue comando2.<br />

fi<br />

#* Ma anche "niente <strong>di</strong> appropriato".<br />

# Verificatelo per la vostra <strong>di</strong>stribuzione [N.d.T.]<br />

• Una verifica if-grep potrebbe non dare i risultati attesi in caso <strong>di</strong> errore, quando il testo viene<br />

visualizzato allo stderr invece che allo stdout.<br />

if ls -l file_inesistente | grep -q ’No such file or <strong>di</strong>rectory’<br />

then echo "Il file \"file_inesistente\" non esiste."<br />

fi<br />

Il problema può essere risolto con la re<strong>di</strong>rezione dello stderr allo stdout.<br />

if ls -l file_inesistente 2>&1 | grep -q ’No such file or <strong>di</strong>rectory’<br />

# ^^^^<br />

then echo "Il file \"file_inesistente\" non esiste."<br />

fi<br />

# Grazie a Chris Martin per la precisazione.<br />

• Il comando run-parts è utile per eseguire una serie <strong>di</strong> coman<strong>di</strong> in sequenza, in particolare abbinato a<br />

cron o at.<br />

582

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

Saved successfully!

Ooh no, something went wrong!