#!/bin/bash
-root=$1
-if [[ -z $1 ]] ; then
- echo "Usage: $0 <root>"
- exit 1
-fi
-
-mounts=$(mount | grep " on ${root%/}/" | awk '{print $3}' | tac)
-if [[ -z ${mounts} ]] ; then
- echo "No mounts found ..."
- echo
- mount
- exit 0
-fi
-
-echo "Unmounting: "
-printf '\t%s\n' ${mounts}
-
-printf "OK? [y/N] "
-read v
-[[ ${v} == "y" ]] && sudo umount -v ${mounts}
+umount_one() {
+ mounts=( $(gawk -v p="${root%/}" '$2 ~ "^"p { print $2 }' /proc/mounts | tac) )
+
+ if ! ${toplevel} && [[ ${#mounts[@]} -gt 0 ]] ; then
+ if [[ ${mounts[-1]} == "${root%/}" ]] ; then
+ unset "mounts[-1]"
+ fi
+ fi
+
+ if [[ ${#mounts[@]} -eq 0 ]] ; then
+ if ! ${quiet} ; then
+ echo "No mounts found for ${root}:"
+ mount
+ fi
+ return
+ fi
+
+ if ! ${quiet} ; then
+ echo "Unmounting: "
+ printf '\t%s\n' "${mounts[@]}"
+ fi
+
+ if ${prompt} ; then
+ printf "OK? [y/N] "
+ read v
+ else
+ v=y
+ fi
+ flags=()
+ ${quiet} || flags+=( -v )
+ [[ ${v} == "y" ]] && sudo umount "${flags[@]}" "${mounts[@]}"
+}
+
+main() {
+ if [[ -z $1 ]] ; then
+ echo "Usage: $0 <root>"
+ exit 1
+ fi
+
+ prompt=true
+ toplevel=true
+ quiet=false
+ while [[ $# -gt 0 ]] ; do
+ case $1 in
+ -y) prompt=false;;
+ -s) toplevel=false;;
+ -q) quiet=true;;
+ *) break;;
+ esac
+ shift
+ done
+
+ while [[ $# -gt 0 ]] ; do
+ root=$1
+ shift
+ umount_one "${root}"
+ done
+}
+main "$@"