[nycbug-talk] nifty(1)

Isaac (.ike) Levy ike at blackskyresearch.net
Fri Aug 24 13:49:51 EDT 2012

Hi All,

Keeping the thread alive with some uri/path handling in shell.

A friend forwarded me this seemingly innocuous line:

# provides the concise full path to a shell script's parent dir
(cd "${0%/*}" 2>/dev/null; echo "$PWD" /)

# or my preference, without the trailing /
(cd "${0%/*}" 2>/dev/null; echo "$PWD")

It's the best expression I've seen in shell which:
  - avoids relative/absolute path inconsistencies of using '${0%/*}'
  - is a fine use of subshell ( )
    ($PWD for parent script doesn't get changed)
  - is a clear use of builtin(1) glob expansion

Now, before I go on extolling this one-liner greatness, can anybody school me on a portable/POSIX builtin(1) which provides the same facility, with the same consistency?
(A drink on me at next NYC*BUG meeting if anyone enlightens me on this)

With all that, consider the following fun:

dothere="$(cd "${0%/*}" 2>/dev/null; echo "$PWD")"
echo "$dothere"

# path trimming via shell glob builtin(1) expansion is now reliable and simple,
echo "${dothere%/*}"
# or, eat the exec and go haywire with sed(1):
echo "$dothere" | sed "s/\/[^\/]*$//"
# making it really easy for to work with hier(7) standard dirs in the script,
echo "${dothere%/*}/etc"
echo "${dothere%/*}/var"
# very handy for combinator shell utilities (styled after git(1) etc...)
echo "${dothere%/*}/sbin"


More information about the talk mailing list