在 Linux 中创建指定大小的空文件,推荐以下几种方法(从推荐到备选排序):

### 1. 最推荐:fallocate(最快)

# 创建 1GB 的空文件
fallocate -l 1G filename.img

# 创建 500MB 的空文件
fallocate -l 500M myfile.dat

# 创建精确到字节的大小(例如 1024 字节)
fallocate -l 1024 exactfile.bin

优点:瞬间完成,不实际写入数据(使用稀疏文件),磁盘占用立即生效。

### 2. truncate 命令(同样非常快)

truncate -s 1G filename.img
truncate -s 500M myfile.dat
truncate -s 1024 exactfile.bin

优点:简单直观,支持 K、M、G、T 等单位。

### 3. dd 命令(最传统,兼容性最好)

# 创建 1GB 文件
dd if=/dev/zero of=filename.img bs=1M count=1024 status=progress

# 或者使用更高效的方式
dd if=/dev/zero of=filename.img bs=1G count=1 status=progress

说明:
- bs=1M count=1024 = 1MB × 1024 = 1GB
- status=progress 可以显示进度(较新版本的 dd 支持)

### 4. 使用 head 从 /dev/zero 创建(备选)

head -c 1G /dev/zero > filename.img

### 常用大小单位对照表

| 单位 | 含义 | 示例 |
|------|----------|---------------|
| K | KB | 10K |
| M | MB | 100M |
| G | GB | 2G |
| T | TB | 1T |
| 字节 | 直接写数字 | 1048576 |

---

### 验证文件大小

ls -lh filename.img     # 人性化显示
du -h filename.img # 实际磁盘占用

推荐顺序:fallocate > truncate > dd

Comments

Be the first to add a comment