Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

What is the best way how to empty a bunch of files in bash? As far I've been doing this

echo "" > development.log
echo "" > production.log

I don't really want to delete those files, so rm is not possible. I've tried many things like

echo "" > *.log

but nothing worked.

share|improve this question
add comment

5 Answers 5

up vote 7 down vote accepted

You don't need the echo. Just

>filename

will empty the file. To edit rassie...

for FILE in *.log
do
   >"${FILE}"
done

The quotes and brackets are preferred, as they will correctly handle files with spaces or special characters in them.

share|improve this answer
1  
The one in the loop creates a file called {FILE}. The first quotation mark needs to go before the dollar sign instead of after. –  Dennis Williamson Sep 9 '09 at 16:09
    
Gak! Typo fixed. –  kmarsh Sep 9 '09 at 17:43
add comment
for i in *.log; do > $i; done

Note that if you really want the files to be emptied you have to use no echo at all, see above, or pass echo the -n flag (echo -n)

share|improve this answer
add comment

Just for fun, another variation combining Eric Dennis' find with everybody else's redirection:

find . -name "*.log" -exec sh -c ">{}" \;
share|improve this answer
add comment

A loop could do:

for i in *.log; do echo "" > $i; done
share|improve this answer
5  
We should be using echo with the -n flag to prevent putting a useless \n at the top of the file. –  Zimmy-DUB-Zongy-Zong-DUBBY Sep 9 '09 at 15:18
add comment
for i in *.log; do cp /dev/null $i; done

Or, if you want to recurse:

find . -name "*.log" -exec cp /dev/null {} \;
share|improve this answer
1  
you miss a ". ( 15 chars here :) ) –  AlberT Sep 9 '09 at 15:52
1  
after log –  Dennis Williamson Sep 9 '09 at 16:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.