6

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

require('./script')

and it will always require script relative to 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 to execute script relative to directory where current executing script is located?

I have tried

/bin/bash script.sh

but getting error:

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

Then tried

script.sh

Got this error

line 8: script.sh: command not found

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

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

Another variant to get script dir:

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

then you can call script with

$DIR/script.sh
4

Unfortunately that is the way to go.

Another way (which I prefer) is to cd into the current dir at the beginning of your scripts like this:

cd $(dirname $0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.