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