6

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
  • 325
  • 3
  • 13

5 Answers5

13

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,971
  • 1
  • 15
  • 25
Dan Ionescu
  • 3,135
  • 1
  • 12
  • 17
8

Just truncate it:

truncate -s 0 file
oguz ismail
  • 1
  • 16
  • 47
  • 69
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
  • 130,504
  • 14
  • 57
  • 93
0

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
    `touch` will only update the file stamp of the file if it already exists. If the file does not exist, `touch` will create it, and it will be empty, but that was not the question. – user1010997 Feb 02 '23 at 09:31
0
tar czvf /tmp/empty.tar.gz --files-from=/dev/null --overwrite 

I found a way here

wailinux
  • 139
  • 4
  • 2
    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