Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include bash scripts with relative path? [duplicate]

Tags:

linux

bash

shell

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.

like image 657
Kirill Rud Avatar asked Jan 09 '18 11:01

Kirill Rud


1 Answers

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"
like image 196
iBug Avatar answered Sep 23 '22 21:09

iBug