summaryrefslogtreecommitdiff
path: root/scripts/usbstick.sh
blob: 981699defb430b5f707e78d0f1a2a98f72622b7a (plain)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env bash
# Mounting or Unmounting devices via the terminal
# This script requires that you have sudo installed and that you have sudo rights.
# Create an executable file /usr/local/bin/usbstick.sh:

# Set the number of USB port available
usbCount=4
# ^ You have to create as many directories as USB port available
#   ( e.g. run the commands 'sudo mkdir /mnt/usbstick1'
#   to 'sudo mkdir /mnt/usbstick4' prior to running this script )

# Search for new devices starting by /dev/sdX with X the value of
deviceStart="b" #/dev/sdb
# ^ To list only new devices, you have to jump over the ones
#   already set. If you have 1 main drive (/dev/sda), start with
#   "b" (/dev/sdb) as value for this variable

# Search for new device(s)
lsblk -no NAME,UUID,FSTYPE,LABEL,MOUNTPOINT | grep -e "sd[$deviceStart-z][0-9]" > /tmp/usbstick
deviceCount=$(cat /tmp/usbstick | wc -l)

if [ $deviceCount -eq 0 ]
then
    echo "No new device detected"
    exit 0
fi

echo "Mount/Umount tool"

# Display new device(s) and read user input
i=0
while read -r name uuid fstype label
    do i=$(($i+1));
    echo "    $i)    $uuid $fstype [$label]"
done < /tmp/usbstick
echo "    q)    quit"

read -p "Choose the drive to be mount/umount : " input

if [[ "$input" == "Q" || "$input" == "q" ]]
then
    echo "    ---> Exiting"
    exit 0
fi

if [[ $input -ge 1 && $input -le $deviceCount ]]
then
    # Get the device selected by the user
    i=0
    while read -r name uuid fstype label
        do i=$(($i+1));
        [ $i -eq $input ] && break
    done < /tmp/usbstick

    # Check if the device is already mounted
    mountpoint=$(echo $label | grep -o "/mnt/usbstick[1-$usbCount]")

    if [ -z $mountpoint ]
    then
        # Search for the next "mount" directory available
        i=0
        while [ $i -le $usbCount ]
            do i=$(($i+1));
            mountpoint=$(cat /tmp/usbstick | grep -o "/mnt/usbstick$i")
            [ -z $mountpoint ] && break
        done

        if [ $i -gt $usbCount ]
        then
            echo "    ---> Set a higher number of USB port available"
            exit 1
        fi

        # Mount the device
        sudo mount -o gid=users,fmask=113,dmask=002 -U $uuid /mnt/usbstick$i
        echo "    ---> Device $uuid mounted as /mnt/usbstick$i"
    else
        # Unmount the device
        sudo umount $mountpoint
        echo "    ---> Device $uuid unmounted [$mountpoint]"
    fi
    exit 0
else
    echo "    ---> Invalid menu choice"
    exit 1
fi