概念
man文档中的描述:
Shrink or extend the size of each FILE to the specified size
A FILE argument that does not exist is created.
If a FILE is larger than the specified size, the extra data is lost. If a FILE is shorter, it is extended and the extended part (hole) reads as zero bytes
总结下来,功能如下:
- 缩小或扩展文件至指定的大小;
- 文件不存在会被创建;
- 如果文件大于指定的大小,则会丢失额外的数据;
- 如果文件小于指定的大小,则对其进行扩展,并且扩展部分读取为零字节;
格式
truncate <OPTION...> <FILE...>
参数
# 不创建任何文件
-c, --no-create
# 将 SIZE 视为 IO 块数而不是字节数
-o, --io-blocks
# 以 RFILE 为基础尺寸
-r, --reference=<RFILE>
# 设置文件大小
-s, --size=<SIZE>
示例
1)创建一个1024字节的文件;
[root@localhost truncate]# truncate -s 1024 myfile
[root@localhost truncate]# ll
总用量 1
-rwxrwxrwx. 1 root root 1024 8月 13 14:28 myfile
[root@localhost truncate]#
2)将1024字节的文件缩小至512字节;
[root@localhost truncate]# truncate -s 512 myfile
[root@localhost truncate]# ll
总用量 1
-rwxrwxrwx. 1 root root 512 8月 13 14:29 myfile
[root@localhost truncate]#
3)将512字节的文件扩展至2048字节;
[root@localhost truncate]# truncate -s 2048 myfile
[root@localhost truncate]# ll
总用量 2
-rwxrwxrwx. 1 root root 2048 8月 13 14:29 myfile
[root@localhost truncate]#
4)对于已存在的文件测试;
# 创建file1,大小为7个字节(包含换行)
[root@localhost truncate]# touch file1 && echo "mytest" > file1
[root@localhost truncate]# ll file1
-rwxrwxrwx. 1 root root 7 8月 12 14:34 file1
[root@localhost truncate]# cat file1
mytest
# 扩展至30或15字节
[root@localhost truncate]# truncate -s 30 file1
[root@localhost truncate]# cat file1
mytest
[root@localhost truncate]# truncate -s 15 file1
[root@localhost truncate]# cat file1
mytest
# 缩小至4字节,发现换行也被删除了
[root@localhost truncate]# truncate -s 4 file1
[root@localhost truncate]# cat file1
myte[root@localhost truncate]#
5)将现有文件截断为0,不删除文件;
# 适用于将文件大小置为0但不删除文件的场景
[root@localhost truncate]# truncate -s 0 file1
[root@localhost truncate]# ll file1
-rwxrwxrwx. 1 root root 0 8月 13 14:41 file1
[root@localhost truncate]#