5 # Email : hayao@fascode.net
7 # (c) 2019-2021 Fascode Network.
11 # Simple script to unmmount everything under the specified directory
17 script_path="$( cd -P "$( dirname "$(readlink -f "$0")" )" && cd .. && pwd )"
18 tools_dir="${script_path}/tools/"
25 echo "usage ${0} [options] [dir]"
27 echo "Unmount everything under the specified directory"
29 echo " General options:"
30 echo " -f | --force Force umount (No warning)"
31 echo " -d | --debug Enable debug message"
32 echo " -m | --maxdepth Specify the maximum hierarchy (set 0 to no limit)"
33 echo " -h | --help This help message"
34 echo " --nocolor No output color message"
37 # Message common function
38 # msg_common [type] [-n] [string]
40 local _msg_opts=("-a" "umount.sh" "--label-space" "6") _type="${1}"
42 [[ "${1}" = "-n" ]] && _msg_opts+=("-o" "-n") && shift 1
43 [[ "${nocolor}" = true ]] && _msg_opts+=("-n")
44 _msg_opts+=("${_type}" "${@}")
45 "${tools_dir}/msg.sh" "${_msg_opts[@]}" &
48 # Show an INFO message
49 # ${1}: message string
50 msg_info() { msg_common info "${@}"; }
52 # Show an Warning message
53 # ${1}: message string
54 msg_warn() { msg_common warn "${@}"; }
56 # Show an debug message
57 # ${1}: message string
59 [[ "${debug}" = true ]] && msg_common debug "${@}"
63 # Show an ERROR message then exit with status
64 # ${1}: message string
65 # ${2}: exit code number (with 0 does not exit)
67 msg_common error "${1}"
68 [[ -n "${2:-}" ]] && exit "${2}"
71 # Unmount helper Usage: _umount <target>
72 _umount() { if mountpoint -q "${1}"; then umount -lf "${1}"; fi; }
77 if [[ ! -v "target_dir" ]] || [[ "${target_dir}" = "" ]]; then
78 msg_error "Exception error about working directory" 1
80 [[ ! -d "${target_dir}" ]] && return 0
81 while read -r _mount; do
82 if [[ "${force}" = true ]] || [[ "${_mount}" = "${target_dir}"* ]] > /dev/null 2>&1; then
83 msg_debug "Checking ${_mount}"
84 if mountpoint -q "${_mount}"; then
85 msg_info "Unmounting ${_mount}"
86 _umount "${_mount}" 2> /dev/null
89 msg_error "It is dangerous to unmount a directory that is not managed by the script."
92 if (( maxdepth == 0 )); then
93 find "${target_dir}" -mindepth 1 -type d -printf "%p\n" | tac
95 find "${target_dir}" -mindepth 1 -maxdepth "${maxdepth}" -type d -printf "%p\n" | tac
102 OPTS=("d" "f" "h" "m:")
103 OPTL=("debug" "force" "help" "maxdepth:" "nocolor")
104 if ! OPT=$(getopt -o "$(printf "%s," "${OPTS[@]}")" -l "$(printf "%s," "${OPTL[@]}")" -- "${@}"); then
109 msg_debug "Argument: ${OPT}"
139 msg_error "Invalid argument '${1}'"
147 if (( ! "${EUID}" == 0 )); then
148 msg_error "This script must be run as root." "1"
152 if [[ -z "${1+SET}" ]]; then
153 msg_error "Please specify the target directory." "1"
155 target_dir="$(realpath "${1}")"