Skip to content

Instantly share code, notes, and snippets.

@pirpyn
Created February 24, 2020 13:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pirpyn/487fa1a694215954e9bf4b4e222c54b7 to your computer and use it in GitHub Desktop.
Save pirpyn/487fa1a694215954e9bf4b4e222c54b7 to your computer and use it in GitHub Desktop.
Automatic USB drive mounting in WSL
#!/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