How to Limit the Size of a Folder in Linux

BobAnkh published on
1 min, 196 words

Categories: Linux

Use the image file mounting method to limit the size of the folder in Linux.

Mount the image file to limit the size of the folder, and it can be easily unmounted when not needed.

你可以在这里查看本文的中文版本。

Mount

  1. First, create a disk image file of the specified size

    dd if=/dev/zero of=/root/disk.img bs=2M count=512
    

    The input device used here is /dev/zero, which can provide unlimited characters. Here we create a 1GB disk image.

  2. Mount the image file as a device

    losetup /dev/loop0 /root/disk.img
    

    If loop0 is already in use, you can also use loop1, loop2, etc.

  3. Make filesystem for the device

    mkfs.ext3 /dev/loop0
    
  4. Mount as a folder

    mount -t ext3 /dev/loop0 /mnt/disk1
    

    This way, the /mnt/disk1 folder can only use 1GB of space.

Unmount

  1. First unmount the folder

    umount /mnt/disk1
    
  2. Then unmount the device

    losetup -d /dev/loop0
    
  3. Finally, delete the image file if not needed

    rm -f /root/disk.img