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.
Asked
Active
Viewed 2,766 times
5

HopelessN00b
- 53,795
- 33
- 135
- 209

pygorex1
- 1,181
- 2
- 9
- 10
6 Answers
14
>output-file
-- shortest possible version.

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

pts
- 435
- 1
- 5
- 16
2
You may do easy :)
:>output-file

Ali Mezgani
- 3,850
- 2
- 24
- 36
-
This is short and it works in all major shells I use (bash, dash, zsh, pdksh, tcsh). – pts Dec 02 '09 at 22:31
-
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
).

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

Evan Anderson
- 141,881
- 20
- 196
- 331
0
echo -n > YOURFILE
will remove file contents and keep the file, structure and permission intact.