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.

Here's a simple one. How do I truncate an existing file in linux? That is, how do I empty the contents of the file but keep the file. I can always delete the file then touch it but I was wondering if there's a single command that'll get the job done.

share|improve this question
add comment

5 Answers

up vote 11 down vote accepted

>output-file -- shortest possible version.

share|improve this answer
1  
accepted for shortness - btw what does the extra colon do in :>output-file ? –  pygorex1 Dec 2 '09 at 21:06
    
No idea; probably best to ask mezgani since he was the one who suggested it. –  womble Dec 2 '09 at 21:26
    
colon's a noop –  Xepoch Dec 2 '09 at 21:29
    
This is the only correct answer. –  Dennis Williamson Dec 2 '09 at 21:42
    
@Xepoch: Thanks; I couldn't find it mentioned in bash(1), it's too common a character. I suspected it was something like that, though. –  womble Dec 2 '09 at 22:06
add comment

This solution is more efficient than cat, because it doesn't create a subprocess (in addition to the shell process):

true >output-file
share|improve this answer
add comment

You may do easy :)


:>output-file

share|improve this answer
    
This is short and it works in all major shells I use (bash, dash, zsh, pdksh, tcsh). –  pts Dec 2 '09 at 22:31
    
yep, i think that not work on ksh –  mezgani Dec 2 '09 at 23:03
add comment

I'm sure a harder-core *nix person will have a better idea, but I've always done:

cat /dev/null > output-file

To truncate files.

share|improve this answer
add comment

echo -n > YOURFILE
will remove file contents and keep the file, structure and permission intact.

share|improve this answer
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.