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.

Re<strong>di</strong>rezione<br />

Capitolo 23. Funzioni<br />

Ecco un altro esempio <strong>di</strong> “ cattura” del “valore <strong>di</strong> ritorno” <strong>di</strong> una funzione. Per comprenderlo è<br />

necessario conoscere un po’ awk.<br />

durata_mese () # Vuole come argomento il numero<br />

#+ del mese.<br />

{ # Restituisce il numero dei giorni del mese.<br />

Gmese="31 28 31 30 31 30 31 31 30 31 30 31" # Dichiarata come locale?<br />

echo "$Gmese" | awk ’{ print $’"${1}"’ }’ # Trucco.<br />

# ^^^^^^^^^<br />

# Parametro passato alla funzione ($1 -- numero del mese) e poi a awk.<br />

# Awk lo vede come "print $1 . . . print $12" (secondo il numero del mese)<br />

# Modello per il passaggio <strong>di</strong> un parametro a uno script awk incorporato:<br />

# $’"${parametro_script}"’<br />

# È necessaria una verifica <strong>di</strong> correttezza dell’intervallo (1-12)<br />

#+ e dei giorni <strong>di</strong> febbraio per gli anni bisestili.<br />

}<br />

# ----------------------------------------------<br />

# Esempio <strong>di</strong> utilizzo:<br />

mese=4 # Aprile, (4Â ◦ mese).<br />

nr_giorni=$(durata_mese $mese)<br />

echo $nr_giorni # 30<br />

# ----------------------------------------------<br />

Ve<strong>di</strong> anche Esempio A-7.<br />

Esercizio: Utilizzando le conoscenze fin qui acquisite, si estenda il precedente esempio dei<br />

numeri romani in modo che accetti un input arbitrario maggiore <strong>di</strong> 255.<br />

Re<strong>di</strong>rigere lo st<strong>di</strong>n <strong>di</strong> una funzione<br />

Una funzione è essenzialmente un blocco <strong>di</strong> co<strong>di</strong>ce, il che significa che il suo st<strong>di</strong>n può essere<br />

re<strong>di</strong>retto (come in Esempio 3-1).<br />

Esempio 23-11. Il vero nome dal nome utente<br />

#!/bin/bash<br />

# realname.sh<br />

# Partendo dal nome dell’utente, ricava il "vero nome" da /etc/passwd.<br />

CONTOARG=1 # Si aspetta un argomento.<br />

E_ERR_ARG=65<br />

file=/etc/passwd<br />

modello=$1<br />

457

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

Saved successfully!

Ooh no, something went wrong!