0

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 ?

2
  • you can call file name directly like : ../../ccc/eee/2.sh . or ./folder_aaa/ccc/eee/2.sh or via bash command like : bash ../../ccc/eee/2.sh Commented Apr 21, 2014 at 20:05
  • you should not end a path with a / unless you plan on referencing a file within that directory: OK: thing=/usr/bin/echo, NOT OK: thing=/usr/bin/, OK: thing=/usr/bin Commented Apr 21, 2014 at 20:24

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.