#!/bin/bash
-if [[ -z $1 ]] ; then
- echo "Usage: $0 <root>"
- exit 1
-fi
-
-prompt=true
-case $1 in
--y) prompt=false; shift;;
-esac
-
-while [[ $# -gt 0 ]] ; do
-
-root=$1
-shift
-
-mounts=$(gawk -v p="${root%/}" '$2 ~ "^"p { print $2 }' /proc/mounts | tac)
-if [[ -z ${mounts} ]] ; then
- echo "No mounts found ..."
- echo
- mount
- continue
-fi
-
-echo "Unmounting: "
-printf '\t%s\n' ${mounts}
-
-if ${prompt} ; then
- printf "OK? [y/N] "
- read v
-else
- v=y
-fi
-[[ ${v} == "y" ]] && sudo umount -v ${mounts}
-
-done
+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 "$@"