4

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.

5 Answers 5

13

>output-file -- shortest possible version.

5
  • 1
    accepted for shortness - btw what does the extra colon do in :>output-file ?
    – pygorex1
    Dec 2, 2009 at 21:06
  • No idea; probably best to ask mezgani since he was the one who suggested it.
    – womble
    Dec 2, 2009 at 21:26
  • colon's a noop
    – Jé Queue
    Dec 2, 2009 at 21:29
  • This is the only correct answer. Dec 2, 2009 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, 2009 at 22:06
2

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

true >output-file
2

You may do easy :)


:>output-file

2
  • This is short and it works in all major shells I use (bash, dash, zsh, pdksh, tcsh).
    – pts
    Dec 2, 2009 at 22:31
  • yep, i think that not work on ksh Dec 2, 2009 at 23:03
0

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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