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 29. Debugging<br />

sh -x nomescript visualizza il risultato <strong>di</strong> ogni comando, ma in modo abbreviato. Equivale ad<br />

inserire nello script set -x o set -o xtrace.<br />

Inserire set -u o set -o nounset nello script permette la sua esecuzione visualizzando, però,<br />

il messaggio d’errore "unbound variable" ogni volta che si cerca <strong>di</strong> usare una variabile non<br />

<strong>di</strong>chiarata.<br />

4. L’uso <strong>di</strong> una funzione “assert”, per verificare una variabile o una con<strong>di</strong>zione, in punti critici dello<br />

script. (È un’idea presa a prestito dal C.)<br />

Esempio 29-4. Verificare una con<strong>di</strong>zione con una funzione “assert”<br />

#!/bin/bash<br />

# assert.sh<br />

assert () # Se la con<strong>di</strong>zione è falsa,<br />

{ #+ esce dallo script con un messaggio d’errore.<br />

E_ERR_PARAM=98<br />

E_ASSERT_FALLITA=99<br />

}<br />

if [ -z "$2" ] # Non sono stati passati abbastanza parametri.<br />

then<br />

return $E_ERR_PARAM # Non fa niente.<br />

fi<br />

numriga=$2<br />

if [ ! $1 ]<br />

then<br />

echo "Assert \"$1\" fallita:"<br />

echo "File \"$0\", riga $numriga"<br />

exit $E_ASSERT_FALLITA<br />

# else<br />

# return<br />

# e continua l’esecuzione dello script.<br />

fi<br />

a=5<br />

b=4<br />

con<strong>di</strong>zione="$a -lt $b" # Messaggio d’errore ed uscita dallo script.<br />

# Provate ad impostare "con<strong>di</strong>zione" con<br />

#+ qualcos’altro, e vedete cosa succede.<br />

assert "$con<strong>di</strong>zione" $LINENO<br />

# La parte restante dello script verrà eseguita solo se "assert" non fallisce.<br />

# Alcuni coman<strong>di</strong>.<br />

518

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

Saved successfully!

Ooh no, something went wrong!