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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

getopt<br />

if [ $# -lt $MINARG ]; then<br />

echo<br />

echo "Argomenti insufficienti."<br />

echo<br />

visualizza_help<br />

exit $E_ERR_ARG<br />

fi<br />

# Verifica l’esistenza del file.<br />

if [ ! -f $FILE ]; then<br />

echo "Il file \"$FILE\" non esiste."<br />

exit $E_ERR_ARG<br />

fi<br />

Capitolo 12. Filtri, programmi e coman<strong>di</strong> esterni<br />

# Conteggio delle occorrenze.<br />

for n in ‘seq $LETTERE‘; do<br />

shift<br />

if [[ ‘echo -n "$1" | wc -c‘ -eq 1 ]]; then # Verifica dell’argomento.<br />

echo "$1" -\> ‘cat $FILE | tr -cd "$1" | wc -c‘ # Conteggio.<br />

else<br />

echo "$1 non è un carattere singolo."<br />

fi<br />

done<br />

exit $?<br />

# Lo script ha esattamente la stessa funzionalità <strong>di</strong> letter-count2.sh,<br />

#+ ma un’esecuzione più veloce.<br />

# Perché?<br />

#<br />

# [N.d.T.] case sensitive = <strong>di</strong>fferenziazione tra lettere minuscole e maiuscole.<br />

getopt verifica le opzioni, precedute da un trattino, passate da riga <strong>di</strong> comando. È il comando<br />

esterno corrispondente al builtin <strong>di</strong> <strong>Bash</strong> getopts. getopt, usato con l’opzione -l, permette la<br />

gestione delle opzioni estese nonchè il rior<strong>di</strong>no dei parametri.<br />

Esempio 12-51. Utilizzo <strong>di</strong> getopt per analizzare le opzioni passate da riga <strong>di</strong> comando<br />

#!/bin/bash<br />

# Usare getopt<br />

# Provate ad invocare lo script nei mo<strong>di</strong> seguenti:<br />

# sh ex33a.sh -a<br />

# sh ex33a.sh -abc<br />

# sh ex33a.sh -a -b -c<br />

# sh ex33a.sh -d<br />

329

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

Saved successfully!

Ooh no, something went wrong!