Created
June 2, 2017 14:31
-
-
Save jcbrinfo/af87cf139715d90867c6512da1b34123 to your computer and use it in GitHub Desktop.
`dirname` in POSIX SH
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /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