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.

units<br />

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

Il comando mcookie fornisce un altro metodo, ancora, per generare un nome <strong>di</strong> file “univoco” .<br />

Esempio 12-56. Generatore <strong>di</strong> nomi <strong>di</strong> file<br />

#!/bin/bash<br />

# tempfile-name.sh: generatore <strong>di</strong> nomi <strong>di</strong> file temporanei<br />

STR_BASE=‘mcookie‘ # magic cookie <strong>di</strong> 32-caratteri.<br />

POS=11 # Posizione arbitraria nella stringa magic cookie.<br />

LUN=5 # Ottiene $LUN caratteri consecutivi.<br />

prefisso=temp # È, dopo tutto, un file "temporaneo".<br />

# Per una maggiore "unicità", generate il prefisso del<br />

#+ nome del file usando lo stesso metodo del<br />

#+ suffisso, <strong>di</strong> seguito.<br />

suffisso=${STR_BASE:POS:LUN}<br />

# Estrae una stringa <strong>di</strong> 5-caratteri, iniziando dall’11a<br />

#+ posizione.<br />

nomefile_temp=$prefisso.$suffisso<br />

# Crea il nome del file.<br />

echo "Nome del file temporaneo = "$nomefile_temp""<br />

# sh tempfile-name.sh<br />

# Nome del file temporaneo = temp.e19ea<br />

# Confrontate questa tecnica per generare nomi <strong>di</strong> file "univoci"<br />

#+ con il metodo ’date’ usato in ex51.sh.<br />

exit 0<br />

Questa utility esegue la conversione tra <strong>di</strong>fferenti unità <strong>di</strong> misura. Sebbene normalmente venga<br />

invocata in modalità interattiva, units può essere utilizzata anche in uno script.<br />

Esempio 12-57. Convertire i metri in miglia<br />

#!/bin/bash<br />

# unit-conversion.sh<br />

converte_unità () # Vuole come argomenti le unità da convertire.<br />

{<br />

cf=$(units "$1" "$2" | sed --silent -e ’1p’ | awk ’{print $2}’)<br />

# Toglie tutto tranne il reale fattore <strong>di</strong> conversione.<br />

echo "$cf"<br />

338

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

Saved successfully!

Ooh no, something went wrong!