This question already has an answer here:

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.

marked as duplicate by B Layer, Jeff Schaller, mdpc, thrig, steve Feb 3 '18 at 10:30

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    If you are sourcing the script then $0 will be the name of the shell, e.g. /bin/bash. unix.stackexchange.com/questions/4650/… – B Layer Feb 2 '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 5 '18 at 9:06

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 ]}
  • it works for me but without the {}, like this $BASH_SOURCE[-1] – WooWapDaBug Feb 5 '18 at 9:03
  • 1
    @WooWapDaBug Are you saying it doesn't work with ${BASH_SOURCE[-1]}? Using $BASH_SOURCE[-1] would give you a file path (potentially the wrong one) with a trailing [-1] at the end. – Kusalananda Feb 5 '18 at 11:09
  • you are right. I don't know what was causing the problem then. – WooWapDaBug Feb 5 '18 at 11:57
  • 1
    @WooWapDaBug Right. Some digging after release notes etc. resulted in an update to my answer. – Kusalananda Feb 5 '18 at 13:22
  • 1
    @WooWapDaBug It seems to work, yes. – Kusalananda Feb 5 '18 at 14:27

If i correctly understand you, this should work:

echo $whereami
  • The problem is that I could be executing the script from a different folder – WooWapDaBug Feb 2 '18 at 13:44
  • Hmm. Yes you are right. This code work if you in the same path wih script. – Burak Talha Bolat Feb 2 '18 at 13:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.