0

I have a small app I'm building and when I hand it off to other team members to work on I'd like to abstract out them having to execute the python script with args directly, and instead have them call on a shell script to do it automatically. Repo structure below:

src/
    app.py
    module_name.py
scripts/
    runAppWithArgs.sh

In runAppWithArgs.sh, I thought to cd ../src and then execute my python code, however I found that if I called on the script as ./scripts/runAppWithArgs.sh (i.e from the top-level directory) since the 'working directory' isn't scripts/, I'm getting errors because it doesn't know how to cd into src/ correctly.

What is the fix for this? At a high level I would like to "assert" that the shell script is running in the right directory context, and the only workaround i can think of seems kind of hacky where I try to parse out the working directory from pwd and then move to the correct directory as-needed, although I think that will require some hard coding that I'm not comfortable doing.

Any pointers would be appreciated!

Ethan Fox
  • 159
  • 1
  • 15
  • 2
    [Get the source directory of a Bash script from within the script itself](https://stackoverflow.com/questions/59895/get-the-source-directory-of-a-bash-script-from-within-the-script-itself) – Cyrus Sep 05 '19 at 17:17

2 Answers2

2

Typically in my scripts i do:

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

The dirname extract directory from a path. The readlink -f resolves any symlinks. $0 is (should be) the path to your script. So even If a user creates a symlink to your script, such dir should be ok. Then just:

 cd "$dir"
 ../src/python_script.py

or just:

 "$dir"/../src/python_script.py
KamilCuk
  • 69,546
  • 5
  • 27
  • 60
0

You can assert that "src" exists at a given context with if [ -d src ]; then ... (watch out for the spaces for they are essential). And so you can run the python files with its corresponding path.