Skip to content

Instantly share code, notes, and snippets.

@szapp
Last active October 11, 2019 08:49
Show Gist options
  • Save szapp/314a3a82c3cf9b4452a0d417bbfefa97 to your computer and use it in GitHub Desktop.
Save szapp/314a3a82c3cf9b4452a0d417bbfefa97 to your computer and use it in GitHub Desktop.
Safely eject removable devices from command line (linux)
#!/bin/bash
# Equivalent to safely removing devices
# The parameter is (part of) the mountpoint
mountpoint=$1
if [[ -z "$mountpoint" ]] || [[ "$mountpoint" == "--help" ]] ; then
echo "Usage: ${0##*/} mountpoint"
exit 1
fi
# Remove trailing slash
if [[ "${mountpoint: -1}" == "/" ]]; then
mountpoint=${mountpoint:0:-1}
fi
# Check mountpoint by filesystem
if [[ ! -d "$mountpoint" ]] && [[ ! -d "/media/${mountpoint}" ]] && [[ ! -d "/mnt/${mountpoint}" ]]; then
echo "Mountpoint not found."
exit 2
fi
# Get partition name from mountpoint
partionname=$(mount | grep "${mountpoint}" | cut -d ' ' -f 1)
if [[ -z "$partionname" ]] || [[ "${#partionname}" -lt "8" ]]; then
echo "Mountpoint not found."
exit 3
fi
# Get device name and all associated partitions
if [[ $partionname = *[[:digit:]] ]]; then
devicename=${partionname:0:-1}
partitionlist=$(ls -1 $devicename*)
numpartions=$(echo $partitionlist | grep -o ' ' | wc -l)
# Iterate over all partitions of the device
for ((i=1; i<=$numpartions; i++)); do
udisksctl unmount -b ${devicename}${i}
if [[ "$?" -ne 0 ]]; then
flist=$(lsof | head -n1 && lsof | grep ${mountpoint} --color=NEVER)
fnr=$(echo -e "${flist}" | wc -l)
if [[ "$fnr" -gt 1 ]]; then
echo -e "${flist}"
fi
exit 4
fi
done
else
devicename=$partionname
udisksctl unmount -b ${devicename}
if [[ "$?" -ne 0 ]]; then
flist=$(lsof | head -n1 && lsof | grep ${mountpoint} --color=NEVER)
fnr=$(echo -e "${flist}" | wc -l)
if [[ "$fnr" -gt 1 ]]; then
echo -e "${flist}"
fi
exit 4
fi
fi
# Lastly power off the device
udisksctl power-off -b ${devicename}
if [[ "$?" -eq 0 ]]; then
# For safety wait 500 ms
sleep 0.5
echo "${devicename} may now be unplugged."
else
exit 5
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment