0

I have a script that I call via . ./env/setenv.sh. In this script, I'm calling a python script that's also located in ./env/.

My current directory is along the lines of ~/dev/project/ and I'm calling into ~/dev/project/env via . ./env/setenv.sh

My attempts (${dirname $0}) to reference the location of setenv.sh from within itself hasn't been successful, because my current working directory is considered /bin rather than ~/dev/project/env/ (I assume due to me sourcing it with .)

What other options do I have for referencing the current working directory of the setenv.sh script, so that it can call my .py script from within the same directory?

e.g.,

WORKING_DIR=$(dirname "$0")
echo $WORKING_DIR
export VAR=$(python $WORKING_DIR/script.py)"

When called via . ./env/setenv.sh prints: /bin, and can't locate script.py

MrDuk
  • 1,597
  • The current working directory is the directory where relative filenames start from. It should be available in $PWD. But that's not what you're looking for, instead, you seem to be looking for the location of the currently executed script file. – ilkkachu Jul 31 '19 at 18:39

1 Answers1

3

If you're using bash, this should work:

$ cat env/setenv.sh 
WORKING_DIR="$(dirname "${BASH_SOURCE[0]}")"
printf '%s is located in directory %s\n' \
         "$(basename "${BASH_SOURCE[0]}")" "$(dirname "${BASH_SOURCE[0]}")"

PYT_FILE="$WORKING_DIR/script.pyt"

printf 'Python script %s is located in directory %s\n' \
         "$(basename "${PYT_FILE}")" "$(dirname "${PYT_FILE}")"

printf 'Path to Python script is %s\n' "${PYT_FILE}"

$ . ./env/setenv.sh 
setenv.sh is located in directory ./env
Python script script.pyt is located in directory ./env
Path to Python script is ./env/script.pyt
Jim L.
  • 7,997
  • 1
  • 13
  • 27
  • Thanks! This returns the current directory, but not the path to it -- how can I get it in the format that would let me do "$(python $WORKING_DIR/script.pyt)"? – MrDuk Jul 31 '19 at 18:14
  • It already is in that format. Updated. – Jim L. Jul 31 '19 at 18:36