truncate -s:把文件调整为精确大小

用 coreutils 的 truncate 在 Linux 上秒级清空日志或预分配稀疏磁盘镜像。

Linux稀疏文件truncate 截断文件文件中风险
执行 truncate -s 0 文件 清空文件,或 truncate -s 10G 文件 瞬间扩展到 10 GiB 而不写零。

01命令

命令
$ truncate -s 0 app.log && truncate -s 10G swapfile.img

02作用说明

truncate 底层调用 truncate(2) 系统调用,因此扩展文件几乎零开销——多出的空间是稀疏的零洞,只有真正写入时文件系统才会分配。这使它成为清空持续增长的日志(truncate -s 0 保留 inode,运行中的进程不用重开文件)或毫秒级预分配 10G swap/虚拟机镜像的即时手段。还支持相对大小:-s +5G 增大、-s -1G 缩小。

03风险

风险中风险
!注意: 缩小文件会静默丢弃新大小之后的所有内容——没有确认,也无法恢复。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

  • truncate(1) — Arch Linux manual
    Arch Linux · technical · 2026-09-17
    依据: -s SIZE sets the file size exactly; supports K/M/G/T suffixes and +/- relative sizes
  • truncate(2) — Linux manual page
    man7.org · technical · 2026-09-17
    依据: System call semantics: file is extended with zeros or reduced, losing data beyond the new size

最后验证: 2026-09-17 · 分类: 文件与文件夹

06相关方案