Shell – How to execute a script located in the same directory as the current script

shell-script

Why are shell scripts are so hard to develop? In NodeJS I could simply do:

require('./script')

and it will always require script relative to the current script. But if I try that in shell/bash:

./script.sh

it will look for script relative to cwd (pwd). Seems the dot means cwd (pwd) and not the directory where current script is located as I was expecting.

line 8: ./script.sh: No such file or directory

How can I execute a script relative to the directory where the current executing script is located?

I have tried

/bin/bash script.sh

but I get the error:

/bin/bash: script.sh: No such file or directory

Then I tried

script.sh

Got this error

line 8: script.sh: command not found

Only the following solution worked fine, but the problem is that it is unreadable:

$("$(dirname "$(realpath "$0")")/script.sh")

Best Answer

Another variant to get script dir:

DIR="$(cd "$(dirname "$0")" && pwd)"

then you can call script with

$DIR/script.sh
Related Question