Many thanks to Michael Heidelbach for providing a script to safely unplug an external hard drive on KDE. For some reason, this bug is long standing…

Installation

Put the file usb-drive-eject in a directory (I’m putting it in ~/.local/bin), with this content

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/bin/bash

declare -A disks=()

## Unmount all USB drives
if [ $# -eq 0 ]; then
    drives=( $(pushd /dev/disk/by-path &>/dev/null; ls -1 | grep -oE '[a-zA-Z0-9:.-]+usb[a-zA-Z0-9:.-]+'|xargs realpath 2>/dev/null; popd &>/dev/null) )
    for d in "${drives[@]}"; do 
        echo "Will unmount $d" >&2
        echo disk:${d//[0-9]} >&2
        disks["${d//[0-9]}"]=true
    done
## Unmount 1 disk
else
    for d in "$@"; do
        disks["${d//[0-9]}"]=true
    done
fi

## Leave if no disks
if [ ${#disks[*]} -eq 0 ]; then 
    echo "Nothing to do" >&2
    exit
fi

##Pattern for mtab
pattern="($(echo "${!disks[@]}"|tr ' ' '|'))[[:digit:]]+[[:space:]]"

##Unmount partitions
for d in $(grep -oE "$pattern" /etc/mtab); do 
    echo "Unmounting $d" >&2
    if udisksctl unmount -b "$d"; then 
        kdialog --passivepopup "Unmounted $d"
    else
        kdialog --passivepopup "Could not unmount $d"
        disks["${d//[0-9]}"]=false
    fi
done

## Power off disks
for d in ${!disks[@]}; do
    if ${disks["$d"]} && udisksctl power-off -b $d; then 
        echo Will poweroff $d
        kdialog --passivepopup  "Ejected $d\n."
    else
        echo "Cannot poweroff $d"
        kdialog --passivepopup  "WARNING $d is still online\n."
    fi
done

Set the executable permission on it

chmod u+x ~/.local/bin/usb-drive-eject

Put hdw.usb-drive-eject.desktop in ~/.local/share/solid/actions with the following content

[Desktop Action open]
Exec=$HOME/.local/bin/usb-drive-eject %d
Icon=application-exit
Name=Eject
Name[de]=Auswerfen

[Desktop Entry]
Actions=open;
Type=Service
X-KDE-Action-Custom=true
X-KDE-Solid-Predicate=[[IS StorageVolume AND StorageDrive.removable == 'true'] OR [IS StorageVolume AND StorageVolume.usage == 'FileSystem']]

At this point, when an external HDD is connected, the device manager of KDE (in the taskbar) should show an additional action named “Eject” for the partitions of the external HDD. Unlike the “safely remove” option of KDE, this script actually spins down the disk after unmounting all the partitions.

Since I’ve put the script usb-drive-eject in a folder in the $PATH, I can additionally run it from the terminal.


Comments

comments powered by Disqus