3670

18 分钟

#Bash 的 truncate 命令

truncate OPTION... FILE...

功能

截断(或增大)文件。

类型

可执行文件(/usr/bin/truncate),属于 coreutils

参数

  • OPTION 选项:
    • -c, --no-create - 不要创建文件
    • -o, --io-blocks - 将 SIZE 视作 I/O 块的个数,而不是字节;通常一个 I/O 块是 4096 字节
    • -r, --reference=RFILE - 基于 RFILE 文件的大小
    • -s, --size=SIZE - 调整后的文件大小,默认为字节
    • --help - 显示帮助
    • --version - 显示版本
  • FILE - 文件列表

#示例

绝对大小

$ truncate -s 10k 1.txt # 将 1.txt 的大小设为 10k,文件不存在时自动创建 $ ls -l 1.txt -rw-rw-r-- 1 planc planc 10240 Dec 6 12:27 1.txt $ truncate -s 1 -o 1.txt # 将 1.txt 的大小设为一个 I/O 块 $ ls -l 1.txt -rw-rw-r-- 1 planc planc 4096 Dec 6 12:28 1.txt

相对大小

$ truncate -s 1k 2.txt # 创建一个 1k 大小的文件 $ truncate -r 2.txt 1.txt # 将 1.txt 的大小设为和 2.txt 一样 $ ls -l 1.txt -rw-rw-r-- 1 planc planc 1024 Dec 6 12:30 1.txt $ truncate -r 2.txt -s +1k 1.txt # 将 1.txt 的大小设为比 2.txt 大 1k $ ls -l 1.txt -rw-rw-r-- 1 planc planc 2048 Dec 6 12:32 1.txt

#推荐阅读

#手册

TRUNCATE(1) User Commands TRUNCATE(1) NAME truncate - shrink or extend the size of a file to the specified size SYNOPSIS truncate OPTION... FILE... DESCRIPTION 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 sparse extended part (hole) reads as zero bytes. Mandatory arguments to long options are mandatory for short options too. -c, --no-create do not create any files -o, --io-blocks treat SIZE as number of IO blocks instead of bytes -r, --reference=RFILE base size on RFILE -s, --size=SIZE set or adjust the file size by SIZE bytes --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. SIZE may also be prefixed by one of the following modifying characters: '+' extend by, '-' reduce by, '<' at most, '>' at least, '/' round down to multiple of, '%' round up to multiple of. AUTHOR Written by Padraig Brady. REPORTING BUGS GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT Copyright © 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO dd(1), truncate(2), ftruncate(2) Full documentation <https://www.gnu.org/software/coreutils/truncate> or available locally via: info '(coreutils) truncate invocation' GNU coreutils 9.4 April 2024 TRUNCATE(1)

创建于 2025/12/6

更新于 2025/12/6