0

I'm trying to get the path of the script that I'm sourcing. I'm doing the following:

DIR="$(dirname "$(readlink -f "$0")")"

Nevertheless I get

readlink: invalid option -- 'b'

I'm on a RedHat 6 machine using bash. Not sure if I'm suppose to do this in a different way.

Blasco
  • 264
  • 1
    If you are sourcing the script then $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
  • 1
    ...and if your shell is a login shell, the name willl be something like -bash, hence the readlink command will ultimately be readlink -f -bash, and that explains the error message. – telcoM Feb 05 '18 at 09:06

2 Answers2

1

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 ]}
Kusalananda
  • 333,661
0

If i correctly understand you, this should work:

whereami=$(pwd)
echo $whereami