16

I have 3 scripts:

Script A:

echo "Hey you!"

Script B:

source ./A.sh

Script C:

source ./libs/B.sh

So scripts A and B in folder "libs" and script C use script B from this directory.

Script C throw Error:

./libs/B.sh: line 1: ./A.sh: No such file or directory

How to correct use script "including" in this case?

I understand why this error occurs, but I do not understand how to fix it. Also! I do not want to include with full path as / home /.../libs/A.sh etc. I want to create move-free scripts without permanent editing.

2
  • Remove ./ from the beginning. . <scriptname> and source <scriptname> are same thing. As you mentioned script A and B is in libs directory and I am assuming script C is also in the same directory you don't need to use ./ if all three scripts reside in the same directory. Commented Jan 9, 2018 at 11:24
  • @GauravPathak if scriptname is found in $PATH, that file will be used instead of the one in the current directory. Commented Jun 3, 2022 at 22:22

1 Answer 1

23

You can specify the directory of the script itself. By default a single dot means "current working directory".

Script B, modified version:

source "$(dirname "$0")/A.sh"

Same mod recommended for C:

source "$(dirname "$0")/libs/B.sh"

You can alternatively use ${0%/*} for the same effect as $(dirname "$0")

Or, to make sure it's the full path to the script, use ${BASH_SOURCE[0]}:

Script B, modified:

source "$(dirname "${BASH_SOURCE[0]}")/A.sh"
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! Also this: > source "$(dirname "$0")/libs/B.sh" Doesn't work. But this: > source "$(dirname "${BASH_SOURCE[0]}")/A.sh" Worked correct.
What if you have ../B.sh rather than ./libs/B.sh?
@Erwann The system will resolve it for you, so go ahead and use $(dirname "$0")/../B.sh.
source "${BASH_SOURCE%/*}/<relpath>" will also work if the importing script itself is being sourced (unlike source "${0%/*}/<relpath>") and will win greatly in terms of performance opposed to dirname in a subshell.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.