How to set a file size limit for a directory?

Solution 1:

Usual filesystem quota on ext4 is per-user/group, not per-directory. ZFS can sort-of set a directory quota, by creating a filesystem of a fixed size off a ZFS volume. A simple trick, though, is to create a 2GB file, create a filesystem on it, and mount it at the desired folder:

$ touch 2gbarea
$ truncate -s 2G 2gbarea
$ mke2fs -t ext4 -F 2gbarea
mke2fs 1.43.3 (04-Sep-2016)
Discarding device blocks: done                            
Creating filesystem with 524288 4k blocks and 131072 inodes
Filesystem UUID: bf1b2ee8-a7df-4a57-9d05-a8b60323e2bf
Superblock backups stored on blocks: 
    32768, 98304, 163840, 229376, 294912

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (16384 blocks): done
Writing superblocks and filesystem accounting information: done 

$ sudo mount 2gbarea up    
$ df -h up
Filesystem      Size  Used Avail Use% Mounted on
/dev/loop0      2.0G  6.0M  1.8G   1% /home/muru/up

In any case, filesystem quotas (or methods like this) aren't as user friendly as you want. This method is one-way flexible, in that you can increase the size online, but decreasing it would be hard.

The commands:

  • touch: touch 2gbarea creates an empty file named 2gbarea.
  • truncate: truncate is used to resize files (in this case, I resize the currently empty 2gbarea file to 2 GB using -s 2G).
  • mke2fs: mke2fs creates ext2/3/4 filesystems (in this case, ext4).
  • mount mounts the filesystem on the given directory.
  • df is used to list filesystem usage.