Skip to content

Instantly share code, notes, and snippets.

@jcbrinfo
Created June 2, 2017 14:31
Show Gist options
  • Select an option

  • Save jcbrinfo/af87cf139715d90867c6512da1b34123 to your computer and use it in GitHub Desktop.

Select an option

Save jcbrinfo/af87cf139715d90867c6512da1b34123 to your computer and use it in GitHub Desktop.
`dirname` in POSIX SH
#! /bin/sh
# dirname <path>
#
# Strip the last path component.
#
# Apply the same transformation than `dirname(1)`, but end the resulting path
# with `/`, so it can be safely used inside a `"$(…)"`
#
# Edge cases
# ----------
# Both this implementation and `dirname(1)`:
#
# * Treat `.` and `..` as any other path component. So `dirname a/.` gives
# you `a/` or `a`, not `./`
#
# * Return the current directory (`./` or `.`) for the empty string.
dirname() {
case "$1" in
/)
# Not required, but more elegant than `//`
printf '/'
;;
*/)
printf '%s/' "${1%/*/}"
;;
*/*)
printf '%s/' "${1%/*}"
;;
*)
printf './'
;;
esac
}
for path in "$@"; do
dirname "${path}"
printf '\n'
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment