# Linux Disk Expand Migration

> Guide users through safely expanding Linux disk space by creating new partitions, migrating data, and setting up symlinks. Born from a real emergency when a ROS developer ran out of disk space during project compilation.

- Skill: `quetzal-china/linux-disk-expand-migration` (Agent Skill, multi-file: 3 files)
- Install (CLI): `npx skillmds@latest add quetzal-china/linux-disk-expand-migration`
- Raw SKILL.md: https://api.skillmd.com/api/skills/quetzal-china/linux-disk-expand-migration/raw
- Safety review: CAUTION (external: skill-scanner PASS, skillspector FAIL)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- License: MIT
- Author: quetzal-china (https://skillmd.com/u/quetzal-china)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/quetzal-china/linux-disk-expand-migration

---


## Background Story | 这个 Skill 的由来

> 📝 **真实场景**: 一位 ROS 开发者在编译项目时遭遇磁盘空间告急（/dev/sda5 使用率 78%，仅剩 6.3GB），而 VMware 扩容后的 36GB 未分配空间位于扩展分区之外，GParted 无法直接合并。在 Kimi K2.5 的协助下，通过创建新分区 + 数据迁移 + 软链接的方案，一步步解决了这个问题。
> 
> 💡 **核心思路**: 不追求单分区的"完美"，而是采用"系统盘放软件，数据盘存文件"的实用策略，既解决燃眉之急，又为未来重装系统保留数据便利。

## What I Do

I guide you through safely expanding Linux disk space when your root partition is full but you have unallocated space that cannot be directly merged due to partition layout constraints.

### 典型场景 | Typical Scenario
- Disk expanded in VMware/VirtualBox (e.g., 30GB → 66GB)
- 未分配空间位于扩展分区之外 | Unallocated space exists outside extended partition
- GParted 显示无法跨越边界扩展 | GParted cannot extend root partition across partition boundaries
- **解决方案**: Create new data partition, migrate personal files, use symlinks

## When to Use Me

Use this skill when:
- Root partition (/dev/sda5, /dev/nvme0n1p3, etc.) is nearly full (>70%) ⚠️ 空间告急！
- You have unallocated space that is NOT contiguous with root partition
- GParted shows "cannot resize" or partition boundaries prevent expansion
- You want to separate system and data for easier future maintenance

## Prerequisites

⚠️ **CRITICAL | 重要提醒**: Backup important data before proceeding! 操作前务必备份重要数据！

- Root or sudo access
- GParted installed (`sudo apt install gparted`)
- Basic understanding of Linux filesystems
- SSH or physical access to the machine
- **耐心 | Patience**: 分区操作需要谨慎，一步一步来

## Step-by-Step Workflow

### Phase 1: Assessment | 现状评估

**知己知彼，百战不殆。先摸清磁盘底细：**

1. **Check current disk layout | 查看当前分区布局**
   ```bash
   lsblk -o NAME,SIZE,FSTYPE,MOUNTPOINT,TYPE
   df -h
   ```

2. **Identify data to migrate | 识别可迁移的数据**
   ```bash
   # 看看哪些目录占空间 | Check which directories use space
   for dir in Documents Downloads Pictures Videos Music Projects Desktop; do
       if [ -d "$HOME/$dir" ]; then
           du -sh "$HOME/$dir" 2>/dev/null
       fi
   done
   ```

### Phase 2: Partition Creation (GParted) | 创建新分区

**可视化操作，谨慎为上：**

1. Open GParted: `sudo gparted`
2. Select the correct disk (e.g., /dev/sda) - **选对磁盘！**
3. Identify unallocated space - 找到那块灰色的未分配空间
4. Right-click unallocated space → New
   - Filesystem: ext4 (Linux 最稳定的文件系统)
   - Label: data (或者其他你喜欢的名字)
   - Size: Use maximum available (全部用上！)
5. Apply changes (green checkmark) - 点击绿色对勾执行
6. Note the new partition name (e.g., /dev/sda3) - 记住新分区名

> 💡 **小贴士**: GParted 操作是队列式的，最后一定要点 "Apply" 才生效。等待过程不要强制关机！

### Phase 3: Filesystem Setup | 文件系统设置

**命令行时间，硬核操作：**

1. **Verify new partition | 确认新分区存在**
   ```bash
   lsblk
   # Should show new partition, e.g., /dev/sda3
   ```

2. **Format if not already done by GParted**
   ```bash
   sudo mkfs.ext4 -L data /dev/sdX3  # Replace X with your disk letter
   ```

3. **Create mount point and test mount | 创建挂载点并测试**
   ```bash
   sudo mkdir -p /data
   sudo mount /dev/sdX3 /data
   df -h | grep data
   ```

### Phase 4: Permanent Mount Configuration | 配置永久挂载

**fstab 是 Linux 的"开机启动配置"，别搞错了：**

1. **Get UUID for fstab | 获取 UUID（比设备名更可靠）**
   ```bash
   sudo blkid /dev/sdX3
   # 复制 UUID，等会要用 | Copy the UUID for next step
   ```

2. **Backup fstab | 备份是好习惯**
   ```bash
   sudo cp /etc/fstab /etc/fstab.backup.$(date +%Y%m%d)
   ```

3. **Add mount entry | 添加挂载配置**
   ```bash
   echo 'UUID=YOUR-UUID-HERE  /data  ext4  defaults,noatime  0  2' | sudo tee -a /etc/fstab
   ```

4. **Test fstab configuration | 验证配置正确性**
   ```bash
   sudo mount -a
   df -h | grep data
   ```

> ⚠️ **重要**: 如果 `mount -a` 报错，**不要重启**！先修正 fstab，否则可能进不了系统。

### Phase 5: Data Migration | 数据迁移（重头戏）

**这是最关键的一步，慢工出细活：**

1. **Create directory structure on data partition**
   ```bash
   sudo mkdir -p /data/{Documents,Pictures,Projects,Desktop,Downloads,Videos,Music}
   sudo chown -R $USER:$USER /data
   ```

2. **Migrate data with rsync | 用 rsync 迁移（带备份保留）**
   
   > 💡 **策略**: 先复制，再重命名原目录为 .backup，最后创建软链接。这样出问题还能回滚。
   
   ```bash
   # 示例：迁移 Documents | Example: Migrate Documents
   rsync -avP ~/Documents/ /data/Documents/
   mv ~/Documents ~/Documents.backup
   
   # 对其他目录重复上述操作...
   # Repeat for Pictures, Projects, Desktop, etc.
   ```

3. **Create symbolic links | 创建软链接（透明跳转）**
   ```bash
   ln -s /data/Documents ~/Documents
   ln -s /data/Pictures ~/Pictures
   ln -s /data/Projects ~/Projects
   ln -s /data/Desktop ~/Desktop
   ln -s /data/Downloads ~/Downloads
   ln -s /data/Videos ~/Videos
   ln -s /data/Music ~/Music
   ```

> 🔗 **软链接原理**: 就像 Windows 的快捷方式，但 Linux 应用程序几乎感知不到区别。访问 ~/Documents 自动跳转到 /data/Documents。

### Phase 6: Verification | 验证阶段

**小心驶得万年船，多测试总没错：**

1. **Verify symlinks work | 检查软链接**
   ```bash
   ls -la ~ | grep -E "Documents|Pictures|Projects|Desktop|Downloads|Videos|Music"
   # Should show all as symlinks (lrwxrwxrwx) pointing to /data/*
   # 应该都显示为软链接 -> /data/*
   ```

2. **Test write access | 测试写入权限**
   ```bash
   echo "test" > ~/Downloads/test.txt
   cat /data/Downloads/test.txt  # 直接读底层文件
   rm ~/Downloads/test.txt
   ```

3. **Check disk usage | 检查磁盘使用率**
   ```bash
   df -h
   # 应该看到 / 和 /data 两个文件系统
   ```

### Phase 7: Cleanup | 清理（可选）

**观察几天没问题后再清理，给自己留条后路：**

```bash
# 确认一切正常后，删除备份 | Remove backups after confirming everything works
rm -rf ~/Documents.backup ~/Pictures.backup ~/Projects.backup ~/Desktop.backup
```

## Important Considerations | 重要考虑因素

### ✅ 放在系统盘 / (System Drive)
- Operating system and system files | 系统和程序
- Installed applications and tools | 安装的软件
- Development workspaces (catkin_ws, ros2_ws, etc.) | 开发工作空间
- Configuration files (~/.config, ~/.bashrc, etc.) | 配置文件
- Package managers (apt, pip, cargo, npm caches) | 包管理器缓存

### ✅ 放在数据盘 /data (Data Drive)
- Documents, PDFs, and text files | 文档
- Images and photos | 图片
- Videos and media | 视频
- Downloads and temporary files | 下载
- Archived projects | 归档项目
- Large datasets | 大数据集

### IDE and Application Compatibility | 软件兼容性

**Generally Safe | 通常透明支持**:
- VS Code, JetBrains IDEs (IntelliJ, PyCharm, CLion)
- File managers (Nautilus, Dolphin, Finder)
- Terminal applications

**May Need Reconfiguration | 可能需要重新配置**:
- Recently opened files lists (will show old paths until reopened)
- Hardcoded paths in scripts (check ~/.bashrc, ~/.profile)
- Build artifacts referencing absolute paths (clean and rebuild)

### ROS/Development Specific Notes | ROS/开发特别提示

**If using ROS (Robot Operating System)**:
- Keep catkin_ws, ros2_ws **on system drive** | ROS 工作空间留在系统盘
- Only migrate non-code data (bags, datasets, docs) | 只迁移非代码数据
- Source files should remain on system drive for fast compilation
- Update any hardcoded paths in .vscode/settings.json

> 🐢 **ROS 开发者的忠告**: catkin_make 和 colcon build 会产生大量临时文件，保持它们在 SSD/系统盘上编译速度更快。

## Troubleshooting | 故障排除

### Issue: "Device or resource busy" when unmounting
**Solution**: Ensure no terminal is in /data directory, then:
```bash
sudo lsof /data
sudo umount -l /data  # lazy unmount 懒卸载
```

### Issue: fstab mount fails on boot | 开机挂载失败
**Solution**: Check UUID is correct:
```bash
sudo blkid /dev/sdX3
sudo nano /etc/fstab  # Correct the UUID 修正 UUID
```

### Issue: Symlink already exists (cannot create) | 软链接已存在
**Solution**: 我们遇到的问题！Remove existing directory first:
```bash
# 先检查是否为空
ls -la ~/Downloads/

# 删除空目录或备份内容后
rm -rf ~/Downloads  # ⚠️ Only if empty or backed up!
ln -s /data/Downloads ~/Downloads
```

### Issue: Permission denied on /data
**Solution**: Fix ownership | 修复权限：
```bash
sudo chown -R $USER:$USER /data
```

### Issue: ROS compilation fails after migration | ROS 编译失败
**Solution**: 可能是路径硬编码问题
```bash
# 清理构建目录重新编译
cd ~/catkin_ws
rm -rf build devel
catkin_make
```

## Safety Checklist | 安全检查清单

**开始前 | Before starting**:
- [ ] Important data backed up to external location | 重要数据已备份
- [ ] Can afford downtime if something goes wrong | 可接受可能的宕机时间
- [ ] Have sudo/root access | 有 root 权限
- [ ] Understand this is an advanced operation | 理解这是高级操作

**操作中 | During operation**:
- [ ] Verify each step before proceeding to next | 每步都验证
- [ ] Keep terminal output for reference | 保留终端输出
- [ ] Do not reboot until fstab is verified with `mount -a` | fstab 验证前不重启

**完成后 | After completion**:
- [ ] Test all critical applications | 测试关键应用
- [ ] Verify development environments work | 验证开发环境
- [ ] Confirm backups exist before deleting .backup | 确认有备份再删 .backup

## Example Final State | 最终状态示例

```
/
├── bin, etc, lib, usr, var ...     # System files (root partition 系统盘)
├── home/
│   └── username/
│       ├── .bashrc, .ssh, .config  # User configs (small, keep on system)
│       ├── Documents → /data/Documents/    # Symlink 软链接
│       ├── Downloads → /data/Downloads/    # Symlink
│       ├── Pictures → /data/Pictures/      # Symlink
│       └── ...
└── data/                           # New partition mount 数据盘挂载点
    ├── Documents/
    ├── Downloads/
    ├── Pictures/
    ├── Projects/
    └── ...
```

**磁盘使用情况 | Disk Usage**:
```bash
$ df -h
文件系统        容量  已用  可用 已用% 挂载点
/dev/sda5        29G   22G  6.3G   78% /        # 系统盘，只装软件
/dev/sda3        36G   67M   34G    1% /data    # 数据盘，放个人文件
```

## Post-Operation Monitoring | 后期监控

Set up disk usage monitoring | 设置磁盘监控：
```bash
# Add to ~/.bashrc or ~/.profile
alias diskusage='df -h | grep -E "Filesystem|/dev/sda5|/data"'
alias du-data='du -sh /data/* 2>/dev/null | sort -hr'
```

## When NOT to Use This Approach | 不适用场景

- If unallocated space IS contiguous with root partition → Use GParted resize instead | 未分配空间与根分区连续
- If using LVM → Use lvextend and resize2fs | 使用 LVM 的情况
- If you need single filesystem semantics → Consider merging partitions (requires backup/reinstall) | 需要单一文件系统语义
- On production servers without maintenance windows | 无维护窗口的生产服务器

## Acknowledgments | 致谢

This skill was created based on a real-world disk expansion scenario encountered by a ROS developer. The step-by-step workflow and safety procedures were developed through collaborative problem-solving between the developer and **Kimi K2.5**.

**Key insights from this collaboration**:
- Practical > Perfect: 实用的分离方案比完美的单分区更好
- Safety first: Always backup, always verify
- Transparency: Symlinks provide seamless user experience
- Separation of concerns: System on SSD, data on larger partition

---

**Remember**: When in doubt, backup first! 有疑问，先备份！

