# if '$1' is empty set 'dir' to '.', else '$1'.
dirname() {
  dir=${1:-.}
  dir=${dir%%"${dir##*[!/]}"}
  [ -n "${dir##*/*}" ] && dir=.
  dir=${dir%/*}
  dir=${dir%%"${dir##*[!/]}"}
  printf '%s\n' "${dir:-/}"
}

# _dirname() {
#   # usage: dirname "path"

#   # if '$1' is empty set 'dir' to '.', else '$1'.
#   dir=${1:-.}

#   # strip all trailing forward-slashes '/' from
#   # the end of the string.
#   #
#   # "${dir##*[!/]}": remove all non-forward-slashes
#   # from the start of the string, leaving us with only
#   # the trailing slashes.
#   # "${dir%%"${}"}": remove the result of the above
#   # substitution (a string of forward slashes) from the
#   # end of the original string.
#   dir=${dir%%"${dir##*[!/]}"}

#   # if the variable *does not* contain any forward slashes
#   # set its value to '.'.
#   [ "${dir##*/*}" ] && dir=.

#   # remove everything *after* the last forward-slash '/'.
#   dir=${dir%/*}

#   # again, strip all trailing forward-slashes '/' from
#   # the end of the string (see above).
#   dir=${dir%%"${dir##*[!/]}"}

#   # print the resulting string and if it is empty,
#   # print '/'.
#   printf '%s\n' "${dir:-/}"
# }

# $ dirname ~/Pictures/Wallpapers/1.jpg
# /home/black/Pictures/Wallpapers/

# $ dirname ~/Pictures/Downloads/
# /home/black/Pictures/
