-
Notifications
You must be signed in to change notification settings - Fork 0
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)
fiThe exact function for POSIX is too complex. Refer the answer in https://stackoverflow.com/questions/29832037.
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 useCDPATH[1], [3] -
unset CDPATH: similar toCDPATH=but it seems more reliable in some implementations -
\cd(?): to ignore the alias even ifcdis aliased- (you may use
unalias -ato remove all alias definitions) - but protecting the shell script form alias definitions is another issue
- (you may use
-
>/dev/null 2>&1: here2>&1is not necessary as$()does not capture the standard error -
>/dev/null: not necessary ascdwill not echo whenCDPATHis empty and "$1" (of cd) is not "-". [3][4]