Use ${BASH_SOURCE[-1]}
:
script_dir=$( dirname "$( readlink -f "${BASH_SOURCE[-1]}" )" )
This is an array that contains the source files for the current shell function call stack, and the last element of it will be the source of the main script.
This ought to work regardless of whether the script was sourced with source
or not.
The particular version of bash
that you are using is version 4.2.1. Negative indexes in arrays (that references from the end of the array) were added in version 4.3. To get the same effect as using ${BASH_SOURCE[-1]}
in a pre-4.3 version of bash
, use
${BASH_SOURCE[ ${#BASH_SOURCE[@]} - 1 ]}
$0
will be the name of the shell, e.g./bin/bash
. https://unix.stackexchange.com/questions/4650/determining-path-to-sourced-shell-script?rq=1 – B Layer Feb 02 '18 at 13:56-bash
, hence the readlink command will ultimately bereadlink -f -bash
, and that explains the error message. – telcoM Feb 05 '18 at 09:06