5

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.

6 Answers 6

14

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

0

There is also:

truncate --size 0 file

Available from gnu coreutils (and probably others too).

I think it reads better than >file, and truncate also have more options (see truncate --help).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .