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 />

ls | xargs -p -l gzip comprime con gzip tutti i file della <strong>di</strong>rectory corrente, uno alla<br />

volta, ed attende un INVIO prima <strong>di</strong> ogni operazione.<br />

Suggerimento: Un’interessante opzione <strong>di</strong> xargs è -n NN, che limita a NN il numero degli<br />

argomenti passati.<br />

ls | xargs -n 8 echo elenca i file della <strong>di</strong>rectory corrente su 8 colonne.<br />

Suggerimento: Un’altra utile opzione è -0, in abbinamento con find -print0 o grep -lZ.<br />

Permette <strong>di</strong> gestire gli argomenti che contengono spazi o apici.<br />

find / -type f -print0 | xargs -0 grep -liwZ GUI | xargs -0 rm -f<br />

grep -rliwZ GUI / | xargs -0 rm -f<br />

Entrambi gli esempi precedenti cancellano tutti i file che contengono “GUI”. (Grazie, S.C.)<br />

Esempio 12-5. Creare un file <strong>di</strong> log utilizzando xargs per verificare i log <strong>di</strong> sistema<br />

#!/bin/bash<br />

# Genera un file <strong>di</strong> log nella <strong>di</strong>rectory corrente<br />

#+ partendo dalla fine del file /var/log/messages.<br />

# Nota: /var/log/messages deve avere i permessi <strong>di</strong> lettura<br />

#+ nel caso lo script venga invocato da un utente or<strong>di</strong>nario.<br />

# #root chmod 644 /var/log/messages<br />

RIGHE=5<br />

( date; uname -a ) >>logfile<br />

# Data e nome della macchina<br />

echo ----------------------------------------------------------- >>logfile<br />

tail -$RIGHE /var/log/messages | xargs | fmt -s >>logfile<br />

echo >>logfile<br />

echo >>logfile<br />

exit 0<br />

# Nota:<br />

# ----<br />

# Come ha sottolineato Frank Wang,<br />

#+ gli apici non verificati (siano essi singoli o doppi) nel file sorgente<br />

#+ potrebbero far fare in<strong>di</strong>gestione ad xargs.<br />

#<br />

# Suggerisce, quin<strong>di</strong>, <strong>di</strong> sostituire la riga 15 con la seguente:<br />

# tail -$RIGHE /var/log/messages | tr -d "\"’" | xargs | fmt -s >>logfile<br />

# Esercizio:<br />

235

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

Saved successfully!

Ooh no, something went wrong!