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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With