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 6. Exit ed exit status<br />

...there are dark corners in the Bourne<br />

shell, and people use all of them.<br />

Chet Ramey<br />

Il comando exit può essere usato per terminare uno script, proprio come in un programma in<br />

linguaggio C. Può anche restituire un valore <strong>di</strong>sponibile al processo genitore dello script.<br />

Ogni comando restituisce un exit status (talvolta chiamato anche return status ). Un comando che ha<br />

avuto successo restituisce 0, mentre, in caso <strong>di</strong> insuccesso, viene restituito un valore <strong>di</strong>verso da zero, che<br />

solitamente può essere interpretato come un co<strong>di</strong>ce d’errore. Coman<strong>di</strong>, programmi e utility UNIX<br />

correttamente eseguiti restituiscono come co<strong>di</strong>ce <strong>di</strong> uscita 0, con significato <strong>di</strong> successo, sebbene ci<br />

possano essere delle eccezioni.<br />

In maniera analoga, sia le funzioni all’interno <strong>di</strong> uno script che lo script stesso, restituiscono un exit<br />

status che nient’altro è se non l’exit status dell’ultimo comando eseguito dalla funzione o dallo script. In<br />

uno script, il comando exit nnn può essere utilizzato per inviare l’exit status nnn alla shell (nnn<br />

deve essere un numero decimale compreso nell’intervallo 0 - 255).<br />

Nota: Quando uno script termina con exit senza alcun parametro, l’exit status dello script è quello<br />

dell’ultimo comando eseguito (quello che precede exit).<br />

#!/bin/bash<br />

COMANDO_1<br />

. . .<br />

# Esce con lo status dell’ultimo comando.<br />

ULTIMO_COMANDO<br />

exit<br />

L’equivalente del solo exit è exit $? o, ad<strong>di</strong>rittura, tralasciando semplicemente exit.<br />

#!/bin/bash<br />

COMANDO_1<br />

. . .<br />

# Esce con lo status dell’ultimo comando.<br />

ULTIMO_COMANDO<br />

exit $?<br />

59

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

Saved successfully!

Ooh no, something went wrong!