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.

i=$RANDOM<br />

let "i %= $INTERVALLO" # Genera un numero casuale compreso<br />

#+ tra 0 e $INTERVALLO - 1.<br />

Capitolo 33. Miscellanea<br />

if [ "$i" -lt "$VALMAX" ]<br />

then<br />

echo "i = $i"<br />

./$0 # Lo script genera ricorsivamente una nuova istanza<br />

#+ <strong>di</strong> sé stesso.<br />

fi # Ogni script figlio fa esattamente la stessa<br />

#+ cosa, finché $i non <strong>di</strong>venta uguale a $VALMAX.<br />

# L’uso <strong>di</strong> un ciclo "while", invece della verifica "if/then", provoca problemi.<br />

# Spiegate perché.<br />

exit 0<br />

# Nota:<br />

# ----<br />

# Lo script, per funzionare correttamente, deve avere il permesso <strong>di</strong> esecuzione.<br />

# Questo anche nel caso in cui venga invocato con il comando "sh".<br />

# Spiegate perché.<br />

Esempio 33-9. Un (utile) script che richiama sé stesso ricorsivamente<br />

#!/bin/bash<br />

# pb.sh: phone book<br />

# Scritto da Rick Boivie e usato con il consenso dell’autore.<br />

# Mo<strong>di</strong>fiche effettuate dall’autore de <strong>Guida</strong> ASB.<br />

MINARG=1 # Lo script ha bisogno <strong>di</strong> almeno un argomento.<br />

FILEDATI=./phonebook<br />

# Deve esistere un file dati <strong>di</strong> nome "phonebook"<br />

#+ nella <strong>di</strong>rectory <strong>di</strong> lavoro corrente.<br />

NOMEPROG=$0<br />

E_NON_ARG=70 # Errore <strong>di</strong> nessun argomento.<br />

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

echo "Utilizzo: "$NOMEPROG" filedati"<br />

exit $E_NON_ARG<br />

fi<br />

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

grep $1 "$FILEDATI"<br />

# ’grep’ visualizza un messaggio d’errore se $FILEDATI non esiste.<br />

else<br />

( shift; "$NOMEPROG" $* ) | grep $1<br />

# Lo script richiama sé stesso ricorsivamente.<br />

fi<br />

553

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

Saved successfully!

Ooh no, something went wrong!