Closed olegs closed 6 years ago
Main problem is that $0
depends not on file location, but on first callee file location.
Consider the following example at folder /Users/oleg/test
: files foo.sh
and bar/bar.sh
.
foo.sh
source bar/bar.sh
PROJECT_ROOT=$(project_root)
echo "$PROJECT_ROOT"
bar/bar.sh
function expand_path() {
# expand ".." and "." including trailing case
# based on https://stackoverflow.com/questions/3915040/bash-fish-command-to-print-absolute-path-to-a-file
TARGET_FILE="$(pwd)/$1"
if [ -d "$1" ]; then
# dir
TARGET_FILE="$(cd "$1"; pwd)"
elif [ -f "$1" ]; then
# file
if [[ $1 == */* ]]; then
TARGET_FILE="$(cd "${1%/*}"; pwd)/${1##*/}"
fi
fi
# Compute the canonicalized name by finding the physical path
# for the directory we're in and appending the target file.
PHYS_DIR="$(pwd -P)"
echo "${PHYS_DIR}/${TARGET_FILE}"
}
_PROJECT_ROOT_BAR="$(expand_path "$(dirname $0)")"
echo "_PROJECT_ROOT_BAR: ${_PROJECT_ROOT_BAR}"
project_root() {
echo ${_PROJECT_ROOT_BAR}
}
2 calls results in different project_root
results.
unit-809:test oleg$ bash foo.sh
_PROJECT_ROOT_BAR: /Users/oleg/test
/Users/oleg/test
unit-809:test oleg$ bash bar/bar.sh
_PROJECT_ROOT_BAR: /Users/oleg/test/bar
At the moment
util.sh
script contains the following code:Which is incorrect for many cases (see
downstream
folder) after #40 is introduced