Skip to content

Instantly share code, notes, and snippets.

@deryni
Last active October 16, 2015 21:02
Show Gist options
  • Save deryni/9c67a908778c1a18405b to your computer and use it in GitHub Desktop.
Save deryni/9c67a908778c1a18405b to your computer and use it in GitHub Desktop.
POSIX-ly correct shell-only implementation of `dirname` (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html).
#!/bin/sh
p=$1
alt=$2
skip78=
stripslashes() {
i=$1
while [ "$i" != "$o" ]; do
o=$i
i=${i%/}
done
eval "$2=\$i"
}
[ "$p" = '//' ] || {
case "$p" in
*[!/]*|'')
stripslashes "$p" p
case "$p" in
*/*)
p=${p%/*}
;;
*)
p=.
skip78=skip78
;;
esac
;;
*)
p=/
skip78=skip78
;;
esac
}
[ -n "$skip78" ] || {
{ [ "$p" != '//' ] || [ -z "$alt" ]; } && {
stripslashes "$p" p
: "${p:=/}"
}
}
printf -- %s\\n "$p"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment