Five ways to summarize and share Linux file emptying

  • 2020-05-30 21:42:56
  • OfStack

This article mainly introduces the five methods of Linux file emptying.

1. Use redirection


[root@centos7 ~]# du -h test.txt 
4.0K test.txt
[root@centos7 ~]# > test.txt 
[root@centos7 ~]# du -h test.txt 
0 test.txt

2. Use the true command to redirect to empty the file


[root@centos7 ~]# du -h test.txt 
4.0K test.txt
[root@centos7 ~]# true > test.txt 
[root@centos7 ~]# du -h test.txt 
0 test.txt

3. Use the cat/cp/dd command and the /dev/null device to empty the file


[root@centos7 ~]# du -h test.txt 
4.0K test.txt
[root@centos7 ~]# cat /dev/null > test.txt 
[root@centos7 ~]# du -h test.txt 
 test.txt
###################################################
[root@centos7 ~]# echo "Hello World" > test.txt 
[root@centos7 ~]# du -h test.txt 
4.0K test.txt
[root@centos7 ~]# cp /dev/null test.txt 
cp : whether to cover "test.txt" ?  y
[root@centos7 ~]# du -h test.txt 
 test.txt
##################################################
[root@centos7 ~]# echo "Hello World" > test.txt 
[root@centos7 ~]# du -h test.txt 
4.0K test.txt
[root@centos7 ~]# dd if=/dev/null of=test.txt 
 Record the 0+0  The read 
 Record the 0+0  The write 
0 byte (0 B) Has been copied, 0.000266781  Second, 0.0 kB/ seconds 
[root@centos7 ~]# du -h test.txt 
 test.txt

4. Use the echo command to empty the file


[root@centos7 ~]# echo "Hello World" > test.txt 
[root@centos7 ~]# du -h test.txt 
4.0K test.txt
[root@centos7 ~]# echo -n "" > test.txt ==> To add "-n" Parameter, by default "\n" , which is the carriage return 
[root@centos7 ~]# du -h test.txt 
0 test.txt

5. Empty the file using truncate


[root@centos7 ~]# du -h test.txt 
4.0K test.txt
[root@centos7 ~]# truncate -s 0 test.txt -s Parameter is used to set the size of the file 0 ; 
[root@centos7 ~]# du -h test.txt 
0 test.txt

conclusion


Related articles: