-
-
Save mouadcherkaoui/837ab9a13be2f9ea506d06d99aacf501 to your computer and use it in GitHub Desktop.
Automatic USB drive mounting in WSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
# Small script to automatically mount/unmount USB drive in WSL | |
usage() { | |
cat << EOF | |
usage: $(basename $0) [-h] [-l] [-u|-m] | |
Options: | |
-h | |
Show this message | |
-l | |
List al USB drives with their DeviceID and their VolumeName | |
-u|-m | |
Mount (-m) or unmount (-u) all USB drives to /mnt/deviceid with the same DeviceID (e.g. E:\) as Windows. | |
EOF | |
} | |
mount_usb() { | |
for ((i=1;i<${#DeviceID_list[@]};i++)); do | |
DeviceID=${DeviceID_list[$i]/:}; | |
VolumeName=${VolumeName_list[$i]}; | |
echo "Mounting ${VolumeName} (${DeviceID}:\\) at /mnt/${DeviceID,,}" | |
case ${DeviceID,,} in | |
a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z) | |
mkdir -p /mnt/${DeviceID,,} | |
mount -t drvfs ${DeviceID,,}: /mnt/${DeviceID,,} | |
;; | |
*) | |
echo "error: cannot mount ${VolumeName}: DeviceID ${DeviceID,,} should be a letter from a to z" > /dev/stderr | |
return 2 | |
;; | |
esac | |
done | |
} | |
umount_usb() { | |
for ((i=1;i<${#DeviceID_list[@]};i++)); do | |
DeviceID=${DeviceID_list[$i]/:}; | |
VolumeName=${VolumeName_list[$i]}; | |
echo "Unmounting ${DeviceID}:\\${VolumeName} at /mnt/${DeviceID,,}" | |
if [[ -d /mnt/${DeviceID,,} ]]; then | |
umount /mnt/${DeviceID,,} | |
rmdir /mnt/${DeviceID,,} | |
else | |
echo "error: cannot unmount ${VolumeName}: is not mounted at /mnt/${DeviceID,,}" > /dev/stderr | |
return 3 | |
fi | |
done | |
} | |
list_usb() { | |
{ | |
echo "DeviceID VolumeName" | |
for ((i=2;i<=${#DeviceID_list[@]};i++)); do | |
DeviceID=${DeviceID_list[$i]}; | |
VolumeName=${VolumeName_list[$i]}; | |
echo ${DeviceID} ${VolumeName} | |
done | |
} | column -t | |
} | |
# Global variable used everywhere | |
wmic="/mnt/c/Windows/System32/Wbem/wmic.exe" | |
DeviceID_list=( $( ${wmic} logicaldisk where drivetype=2 get DeviceID | tr '\r\n' ' ' ) ) | |
VolumeName_list=( $( ${wmic} logicaldisk where drivetype=2 get VolumeName | tr '\r\n' ' ' ) ) | |
while getopts huml arg; do | |
case ${arg} in | |
h) | |
usage | |
exit 1 | |
;; | |
u) | |
umount_usb | |
;; | |
m) | |
mount_usb | |
;; | |
l) | |
list_usb | |
;; | |
*) # By default mount everything | |
mount_usb | |
;; | |
esac | |
done | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment