3 ms·
How to get the source directory of a Bash script from within the script itself?
- gjvc 6y agoI don't quite follow every last precaution against "characters other than new lines at the end of a directory name", but I find that these lines of boilerplate do just fine in a modern Linux. (Main assumption is that realpath(1) exists, obv.) I've included a couple of logging functions which don't require external processes for the date as a bonus :-) #! /usr/bin/env bash set -eu # location ------------------------------------------------------------- readonly _REALPATH=$(realpath "${BASH_SOURCE[ 0 ]}") readonly _BASENAME=$(basename "${_REALPATH}") readonly _DIRNAME=$(dirname "${_REALPATH}") readonly _ROOT=$(dirname "${_DIRNAME}") readonly _PREFIX=$(dirname "${_ROOT}") # logging -------------------------------------------------------------- function log { printf "%(%Y-%m-%d)TT%(%H:%M:%S%z)T ${@}\n" -1 ; } function err { printf "%(%Y-%m-%d)TT%(%H:%M:%S%z)T ${@}\n" -1 1>&2 ; }