Mount partition at startup the same way the file manager does it - NOT with /etc/fstab

I want to mount a partition after login the same way the file manager does it when I click an unmounted device under 'Devices'. Ideally, I want to use the same underlying daemon the file manager uses.

It should NOT be mounted via fstab. Basically, the result should be as if I opened the file manager after login and clicked on the device, without the need to elevate rights, unmountable by the user, same access rights, same place in the file hierarchy (/media/user/partitionlabel-or-UUID).

After login - so different devices could be mounted for different users, for example.

How could this be done? A search drowns relevant information in the gazillion answers via /etc/fstab. The one suggested answer for mounting a samba fs at login doesn't help here.


The answer is really easy if you know what to look for. A DE-agnostic way to automount disks at login is to use udisksctl. It is often used to mount loop devices, but it can also mount drives. The necessary polkit rules are already present since udisks2 is used under the hood for the automount mechanisms of the file managers. Therefore, it can be run without elevated access rights.

udisksctl mount -b /dev/sdn1 or udisksctl mount -b /dev/disk/by-label/<disklabel> mounts the disk from the command line under /media/<username>/<diskname or UUID>.

The line udisksctl mount -b /dev/sdn1 2>/dev/null added to the user's ~/.profile, which is run after each graphical, non-graphical or remote login, attempts to mount the disk and fails silently if already mounted so the user is not irritated by an error line.

For completeness, ~/.bash_logout with a udisksctl unmount -b /dev/sdn1 could unmount this disk at logout if desired.

For a broader solution, put this in ~/.profile:

# mount disk with specified label if unmounted and present
userdisks=( "disklabel 1" "disklabel 2" "disklabel 3" )
for disk in "${userdisks[@]}"
do
    if ! lsblk -l | grep -q $disk ; then
        udisksctl mount -b /dev/disk/by-label/$disk
    fi
done

and add this to ~/.bash_logout:

# unmounts disks at last logout of user
count=$(who | grep -c $(whoami))
if [ $count -eq 1 ] ; then
    userdisks=( "disklabel 1" "disklabel 2" "disklabel 3" )
    for disk in "${userdisks[@]}"
    do
        if lsblk -l | grep -q $disk ; then
           udisksctl unmount -b /dev/disk/by-label/$disk
        fi
    done
fi

You have to put all the labels of devices you want to mount in the space-separated userdisks array. Make sure that a label with spaces is surrounded by quotation marks.

This lets the user know that the disk is mounted on the command line, silently skips mounting when disk is already mounted and gives an error when disks are missing.

Only when the last user session gets logged out, the disks are unmounted.

This setup has been a convenient timesaver when logging in via ssh to a laptop with removable devices, for example.