I am trying to set up a virtual drive from a file. This file will then be written to a flash device (not relevant). Because creating and manipulating the virtual drive will be in a script, I need to do it in user space, i.e., not as root. The script is for building and creating an image for a flash device; so, running as root will be problematic.

In order to mount the file as a virtual drive, I added the following line to /etc/fstab:

/home/user/drive.img /home/user/mnt ext4 loop,rw,user,noauto,noexec 0 0

The problem is that when I mount the virtual drive, root takes ownership of ~/mnt, defeating the purpose of mounting it as a regular user.

I know that other file systems allow you to mount while specifying the uid/gid, but the virtual drive must be ext4 to be compatible with an existing process. I tried udisksctl, but it requires root authentication for loopback.

I am going to try mounting then changing ownership (as root) but never unmount it. I will do a 'sync' then take a snapshot of the virtual drive. I do not like it because it is not clean, but it may work for now.


The step you haven't mentioned is how you created the ext4 filesystem, which is the source of the problem. Using mkfs.ext4 /home/user/drive.img will create a root inode owned by root, so when you mount it, it will still belong to root.

A solution is to use debugfs (package e2fsprogs for Fedora) to edit the inode. This example worked for me:

uid=$(id -u)
gid=$(id -g)
rm -f /tmp/ext4fs
truncate -s 50M /tmp/ext4fs
mkfs.ext4 /tmp/ext4fs
debugfs -w -R "set_inode_field . uid $uid" /tmp/ext4fs
debugfs -w -R "set_inode_field . gid $gid" /tmp/ext4fs
# echo '/tmp/ext4fs /tmp/mymnt ext4 loop,rw,user,noauto,noexec' >>/etc/fstab
mkdir -p /tmp/mymnt
mount /tmp/ext4fs
ls -lRa /tmp/mymnt
touch /tmp/mymnt/afile
ls -l /tmp/mymnt
umount /tmp/ext4fs

On mount the ls shows the mount point as

drwxr-xr-x  3 meuh  users  1024 May 15 21:04 .

and allows me to create a file there.

| improve this answer | |
  • Thank you. You taught me one more trick: the use of truncate. I was using dd. Should I be worried that this will be a sparse file when I burn it on the flash part? – Sean Walton May 15 at 22:26
  • Sparseness is an internal optimisation that has no visible externel effects. Remember to tick the answer if it resolves your question so other readers know. – meuh May 16 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.