Question

I have two scripts in undermentioned folders:

  • /folder_aaa/bbb/ddd/1.sh
  • /folder_aaa/ccc/eee/2.sh

I would like to run 2.sh script from 1.sh script. How should I write a path to 2.sh script ?

1.sh:

DIR=/../../ccc/eee/
SCRIPT_NAME="2.sh"

${DIR}/${SCRIPT_NAME}

Is above code (especially dir referention) ok ?

Was it helpful?

Solution

You can't just use ../../<DIRS> because .. will change depending on where you are, that is what $PWD is; rather than where the script using .. is.

Using realpath and dirname

startdir="$(dirname "$(realpath "$0")")"
script="2.sh"
"$startdir"/../../"$script"

Using the absolute path

If you don't have access to realpath and dirname or don't want to use them: if you know that the location of 2.sh and 1.sh will never change, then you should fine using an absolute path to 2.sh

"$HOME"/code/scripts/2.sh

OTHER TIPS

Relative paths should not begin with / (they can, but since / is its own parent, any number of leading /.. are redundant). Your DIR is equivalent to /ccc/eee. So you would want

DIR=../../ccc/eee
SCRIPT_NAME="2.sh"
${DIR}/${SCRIPT_NAME}

However, this assumes that the location of 1.sh will never change relative to 2.sh. You might just use the absolute path of 2.sh instead:

DIR=/folder_aaa/ccc/eee

That, of course, assumes that the absolute path of 2.sh won't change. Which one you use is a matter of preference and how the locations of 1.sh and 2.sh relate to each other.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top