1

which one is the best way to clean or empty a file in Linux? I have to zip ( tar ) a file to an archive and then clean/empty it; this is what I do and it works correctly:

tar -zcvf /mnt/file.tar.gz /mnt/file.txt > /dev/null 2>&1

echo "" > /mnt/file.txt

I'm doing it with echo, probably there is a better way ?

Thanks

DDBE
  • 175
  • 1
  • 12

5 Answers5

6

There are multiple ways to do that:

We presume that our file is called access.log and it's in the current directory:

1.

: > access.log

2.

true > access.log

3.

cat /dev/null > access.log

4.

cp /dev/null access.log

5.

dd if=/dev/null of=access.log

6.

echo -n "" > access.log

7.

echo -n > access.log
Wiimm
  • 2,430
  • 1
  • 13
  • 22
Dan Ionescu
  • 2,694
  • 1
  • 11
  • 14
5

Just truncate it:

truncate -s 0 file
oguz ismail
  • 39,105
  • 12
  • 41
  • 62
2

one option is:

touch passbook.txt

Another option to make empty file in Linux is just type the following command:

> file-name-here
echo '' > filename
ls filename
file filename
1

EDIT(zipping file and nullifying actual file): Taking inspiration from @oguz ismail's fine answer, I am using truncate option with zip of the file too here.

tar -zcvf file.tar.gz file.txt && truncate -s 0 file.txt


I will go with > /mnt/file.txt a bit easier than echo.

RavinderSingh13
  • 117,272
  • 11
  • 49
  • 86
0
tar czvf /tmp/empty.tar.gz --files-from=/dev/null --overwrite 

I found a way here

wailinux
  • 129
  • 4
  • 1
    IMHO I don't think OP is looking to create an empty zip file, he/she is looking for zipping a file and then nullifying actual file, if I got it correctly. – RavinderSingh13 Oct 30 '19 at 08:00