14

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.

Kirill Rud
  • 217
  • 3
  • 9
  • Remove `./` from the beginning. `. ` and `source ` 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. – Gaurav Pathak Jan 09 '18 at 11:24
  • @GauravPathak if `scriptname` is found in `$PATH`, that file will be used instead of the one in the current directory. – tokland Jun 03 '22 at 22:22

1 Answers1

19

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"
iBug
  • 35,554
  • 7
  • 89
  • 134
  • 1
    Thank you! Also this: > source "$(dirname "$0")/libs/B.sh" Doesn't work. But this: > source "$(dirname "${BASH_SOURCE[0]}")/A.sh" Worked correct. – Kirill Rud Jan 09 '18 at 11:58
  • What if you have `../B.sh` rather than `./libs/B.sh`? – Erwann Feb 18 '22 at 10:02
  • 1
    @Erwann The system will resolve it for you, so go ahead and use `$(dirname "$0")/../B.sh`. – iBug Feb 18 '22 at 11:08