Skip to content

scriptdir

zeta709 edited this page Feb 4, 2022 · 1 revision
if [ -n "$BASH_VERSION" ]; then
    # http://stackoverflow.com/questions/59895
    scriptdir="$(unset CDPATH && cd -- "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
elif [ -n "$ZSH_VERSION" ]; then
    # https://stackoverflow.com/questions/9901210
    scriptdir="${${(%):-%x}:A:h}"
else
    # https://stackoverflow.com/questions/29832037
    scriptdir=$(unset CDPATH && cd -- "$(dirname -- "$0")" && pwd -P)
fi

The exact function for POSIX is too complex. Refer the answer in https://stackoverflow.com/questions/29832037.

Note

I collected ideas from various answers and modified the original snippets suggested in the Stackoverflow threads.

  • scriptdir: it shoud be in lower case letters
  • CDPATH=: to not use CDPATH [1], [3]
  • unset CDPATH: similar to CDPATH= but it seems more reliable in some implementations
  • \cd(?): to ignore the alias even if cd is aliased
    • (you may use unalias -a to remove all alias definitions)
    • but protecting the shell script form alias definitions is another issue
  • >/dev/null 2>&1: here 2>&1 is not necessary as $() does not capture the standard error
  • >/dev/null: not necessary as cd will not echo when CDPATH is empty and "$1" (of cd) is not "-". [3][4]

Referencees

  1. http://stackoverflow.com/questions/59895
  2. https://stackoverflow.com/questions/9901210
  3. https://stackoverflow.com/questions/29832037
  4. https://pubs.opengroup.org/onlinepubs/9699919799/utilities/cd.html

Clone this wiki locally