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 12. Filtri, programmi e coman<strong>di</strong> esterni<br />

osinfo.txt:The GPL governs the <strong>di</strong>stribution of the Linux operating system.<br />

Se la ricerca ha avuto successo, grep restituisce come exit status 0. Questo lo rende utile per un<br />

costrutto <strong>di</strong> verifica in uno script, specialmente in abbinamento con l’opzione -q che sopprime<br />

l’output.<br />

SUCCESSO=0 # se la ricerca <strong>di</strong> grep è riuscita<br />

parola=Linux<br />

file=file.dati<br />

grep -q "$parola" "$file"<br />

# L’opzione "-q" non visualizza nulla allo stdout.<br />

if [ $? -eq $SUCCESSO ]<br />

# if grep -q "$parola" "$file" può sostituire le righe 5 - 8.<br />

then<br />

echo "$parola è presente in $file"<br />

else<br />

echo "$parola non è presente in $file"<br />

fi<br />

L’Esempio 29-6 <strong>di</strong>mostra come usare grep per cercare una parola in un file <strong>di</strong> log <strong>di</strong> sistema.<br />

Esempio 12-15. Simulare “grep” in uno script<br />

#!/bin/bash<br />

# grp.sh: Una reimplementazione molto sommaria <strong>di</strong> ’grep’.<br />

E_ERR_ARG=65<br />

if [ -z "$1" ] # Verifica se sono stati passati argomenti allo script.<br />

then<br />

echo "Utilizzo: ‘basename $0‘ modello"<br />

exit $E_ERR_ARG<br />

fi<br />

echo<br />

for file in * # Verifica tutti i file in $PWD.<br />

do<br />

output=$(sed -n /"$1"/p $file) # Sostituzione <strong>di</strong> comando.<br />

if [ ! -z "$output" ] # Cosa succede se si usa "$output"<br />

#+ senza i doppi apici?<br />

then<br />

echo -n "$file: "<br />

257

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

Saved successfully!

Ooh no, something went wrong!