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.

numeroc=$((RANDOM%25+6))<br />

# Generare un numero casuale, sempre nell’intervallo 6 - 30,<br />

#+ ma che deve essere <strong>di</strong>visibile per 3.<br />

numeroc=$(((RANDOM%30/3+1)*3))<br />

# È da notare che questo non sempre funziona.<br />

# Fallisce quando $RANDOM restituisce 0.<br />

# Frank Wang suggerisce la seguente alternativa:<br />

numeroc=$(( RANDOM%27/3*3+6 ))<br />

Capitolo 9. Variabili riviste<br />

Bill Gradwohl ha elaborato una formula più perfezionata che funziona con i numeri positivi.<br />

numeroc=$(((RANDOM%(max-min+<strong>di</strong>visibilePer))/<strong>di</strong>visibilePer*<strong>di</strong>visibilePer+min))<br />

Qui Bill presenta una versatile funzione che restituisce un numero casuale compreso tra due valori<br />

specificati.<br />

Esempio 9-26. Numero casuale in un intervallo dato<br />

#!/bin/bash<br />

# random-between.sh<br />

# Numero casuale compreso tra due valori specificati.<br />

# Script <strong>di</strong> Bill Gradwohl, con mo<strong>di</strong>fiche <strong>di</strong> secondaria importanza fatte<br />

#+ dall’autore del libro.<br />

# Utilizzato con il permesso dell’autore.<br />

interCasuale() {<br />

# Genera un numero casuale positivo o negativo<br />

#+ compreso tra $min e $max<br />

#+ e <strong>di</strong>visibile per $<strong>di</strong>visibilePer.<br />

# Restituisce una <strong>di</strong>stribuzione <strong>di</strong> valori "ragionevolmente casuale".<br />

#<br />

# Bill Gradwohl - 1 Ott, 2003<br />

sintassi() {<br />

# Funzione all’interno <strong>di</strong> una funzione.<br />

echo<br />

echo "Sintassi: interCasuale [min] [max] [multiplo]"<br />

echo<br />

echo "Si aspetta che vengano passati fino a 3 parametri,"<br />

echo "tutti però opzionali."<br />

echo "min è il valore minimo"<br />

echo "max è il valore massimo"<br />

echo "multiplo specifica che il numero generato deve essere un"<br />

echo "multiplo <strong>di</strong> questo valore."<br />

149

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

Saved successfully!

Ooh no, something went wrong!