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.

Capitolo 33. Miscellanea<br />

awk. Se salvato come file eseguibile può essere ripetutamente invocato, nella sua forma originale o<br />

mo<strong>di</strong>ficata, senza l’inconveniente <strong>di</strong> doverlo ri<strong>di</strong>gitare completamente da riga <strong>di</strong> comando.<br />

Esempio 33-1. Shell wrapper<br />

#!/bin/bash<br />

# Questo è un semplice script che rimuove le righe vuote da un file.<br />

# Nessuna verifica d’argomento.<br />

#<br />

# Sarebbe meglio aggiungere qualcosa come:<br />

# E_NOARG=65<br />

# if [ -z "$1" ]<br />

# then<br />

# echo "Utilizzo: ‘basename $0‘ nome-file"<br />

# exit $E_NOARG<br />

# fi<br />

# È uguale a<br />

# sed -e ’/^$/d’ nomefile<br />

# invocato da riga <strong>di</strong> comando.<br />

sed -e /^$/d "$1"<br />

# ’-e’ significa che segue un comando <strong>di</strong> "e<strong>di</strong>ting" (in questo caso opzionale).<br />

# ’^’ in<strong>di</strong>ca l’inizio della riga, ’$’ la fine.<br />

# Verifica le righe che non contengono nulla tra il loro inizio e la fine,<br />

#+ vale a <strong>di</strong>re, le righe vuote.<br />

# ’d’ è il comando <strong>di</strong> cancellazione.<br />

# L’uso del quoting per l’argomento consente <strong>di</strong><br />

#+ passare nomi <strong>di</strong> file contenenti spazi e caratteri speciali.<br />

# Va notato che lo script, in realtà, non mo<strong>di</strong>fica il file <strong>di</strong> riferimento.<br />

# Se avete questa necessità, effettuate la re<strong>di</strong>rezione dell’output.<br />

exit 0<br />

Esempio 33-2. Uno shell wrapper leggermente più complesso<br />

#!/bin/bash<br />

# "subst", uno script per sostituire un nome<br />

#+ con un altro all’interno <strong>di</strong> un file,<br />

#+ es., "subst Smith Jones letter.txt".<br />

ARG=3 # Lo script richiede tre argomenti.<br />

E_ERR_ARG=65 # Numero errato <strong>di</strong> argomenti passati allo script.<br />

if [ $# -ne "$ARG" ]<br />

# Verifica il numero degli argomenti (è sempre una buona idea).<br />

547

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

Saved successfully!

Ooh no, something went wrong!