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 11. Coman<strong>di</strong> interni e builtin<br />

2. La struttura <strong>di</strong> getopts <strong>di</strong>fferisce leggermente da un normale ciclo while perché non è<br />

presente la con<strong>di</strong>zione <strong>di</strong> verifica.<br />

3. Il costrutto getopts sostituisce il deprecato comando esterno getopt.<br />

while getopts ":abcde:fg" Opzione<br />

# Dichiarazione iniziale.<br />

# a, b, c, d, e, f, g sono le opzioni attese.<br />

# I : dopo l’opzione ’e’ in<strong>di</strong>cano che c’è un argomento associato.<br />

do<br />

case $Opzione in<br />

a ) # Fa qualcosa con la variabile ’a’.<br />

b ) # Fa qualcosa con la variabile ’b’.<br />

...<br />

e) # Fa qualcosa con ’e’, e anche con $OPTARG,<br />

# che è l’argomento associato all’opzione ’e’.<br />

...<br />

g ) # Fa qualcosa con la variabile ’g’.<br />

esac<br />

done<br />

shift $(($OPTIND - 1))<br />

# Sposta il puntatore all’argomento successivo.<br />

# Tutto questo non è affatto complicato come sembra .<br />

Esempio 11-19. Utilizzare getopts per leggere le opzioni/argomenti passati ad uno script<br />

#!/bin/bash<br />

# Prove con getopts e OPTIND<br />

# Script mo<strong>di</strong>ficato il 9/10/03 su suggerimento <strong>di</strong> Bill Gradwohl.<br />

# Osserviamo come ’getopts’ elabora gli argomenti passati allo script da<br />

#+ riga <strong>di</strong> comando.<br />

# Gli argomenti vengono verificati come "opzioni" (flag)<br />

#+ ed argomenti associati.<br />

# Provate ad invocare lo script con<br />

# ’nomescript -mn’<br />

# ’nomescript -oq qOpzione’ (qOpzione può essere una stringa qualsiasi.)<br />

# ’nomescript -qXXX -r’<br />

#<br />

# ’nomescript -qr’ - Risultato inaspettato, considera "r"<br />

#+ come l’argomento dell’opzione "q"<br />

# ’nomescript -q -r’ - Risultato inaspettato, come prima.<br />

# ’nomescript -mnop -mnop’ - Risultato inaspettato<br />

# (OPTIND non è atten<strong>di</strong>bile nello stabilire da dove proviene un’opzione).<br />

#<br />

210

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

Saved successfully!

Ooh no, something went wrong!