]> Sergey Matveev's repositories - nnn.git/blob - plugins/nmount
26cf38fc8cb2073960a4921555b75b088985474e
[nnn.git] / plugins / nmount
1 #!/usr/bin/env sh
2
3 # Description: Toggle mount status of a device using pmount
4 #              If the device is not mounted, it will be mounted.
5 #              If the device is mounted, it will be unmounted and powered down.
6 #
7 # Dependencies: lsblk, pmount (optional), udisks2
8 #
9 # Usage: Runs `lsblk` on 'l', exits on 'Return`.
10 #
11 # Notes:
12 #   - The script uses Linux-specific lsblk to list block devices. Alternatives:
13 #       macOS: "diskutil list"
14 #       BSD: "geom disk list"
15 #   - The script uses udisksctl (from udisks2) to power down devices. This is also Linux-specific.
16 #     Users on non-Linux platforms can comment it and use an alternative to power-down disks.
17 #
18 # Shell: POSIX compliant
19 # Author: Arun Prakash Jana
20
21 prompt="device name [e.g. sdXn] ('l'ist, 'q'uit): "
22
23 lsblk
24
25 printf "\nEnsure you aren't still in the mounted device.\n"
26 printf "%s" "$prompt"
27 read -r dev
28
29 while [ -n "$dev" ]; do
30     if [ "$dev" = "l" ]; then
31         lsblk
32     elif [ "$dev" = "q" ]; then
33         exit
34     else
35         if grep -qs "$dev " /proc/mounts; then
36             sync "$(lsblk -n "/dev/$dev" -o MOUNTPOINT | sed "/^$/d")"
37             if type pumount >/dev/null 2>&1; then
38                 pumount "/dev/$dev"
39                 exit_code="$?"
40             else
41                 udisksctl unmount -b "/dev/$dev" --no-user-interaction
42                 exit_code="$?"
43             fi
44             if [ $exit_code -eq 0 ]; then
45                 echo "/dev/$dev unmounted."
46                 if udisksctl power-off -b "/dev/$dev" --no-user-interaction; then
47                     echo "/dev/$dev ejected."
48                 fi
49             fi
50         elif [ -b "/dev/$dev" ]; then
51             if type pmount >/dev/null 2>&1; then
52                 pmount "/dev/$dev"
53                 exit_code="$?"
54             else
55                 udisksctl mount -b "/dev/$dev" --no-user-interaction
56                 exit_code="$?"
57             fi
58             if [ $exit_code -eq 0 ]; then
59                 sleep 1
60                 echo "/dev/$dev mounted to $(lsblk -n "/dev/$dev" -o MOUNTPOINT | sed "/^$/d")."
61             fi
62         else
63             echo "/dev/$dev does not exist or is not a block device."
64         fi
65     fi
66
67     echo
68     printf "%s" "$prompt"
69     read -r dev
70 done