Village
Village

Reputation: 24363

What is the simplest way to delete the contents of a file in BASH?

I need to delete all lines in a file, but leave essentially an empty file with no content and no lines. As best I know, one can do this:

rm file.txt 2> /dev/null
touch file.txt

However, is there a simpler, more canonical solution in BASH?

Upvotes: 10

Views: 10737

Answers (3)

trikelef
trikelef

Reputation: 2204

Another (brutal) way to empty a file would be the following:

cat /dev/null > filename

Upvotes: 6

Kirby Todd
Kirby Todd

Reputation: 11546

You can use truncate.

truncate -s 0 filename

Upvotes: 11

fedorqui
fedorqui

Reputation: 289605

This is a pretty fast way I always use:

> file.txt

It completely empties the file and updates the modification time.

Upvotes: 27

Related Questions