I have two Bash scripts in the same folder (saved somewhere by the user who downloads the entire repository):
script.sh
is run by the userhelper.sh
is required and run byscript.sh
The two scripts should be in the same directory. I need the first script to call the second one, but there are two problems:
- Knowing the current working directory is useless to me, because I don't know how the user is executing the first script (could be with
/usr/bin/script.sh
, with./script.sh
, or it could be with../Downloads/repo/scr/script.sh
) - The script
script.sh
will be changing to a different directory before callinghelper.sh
.
I can definitely hack together Bash that does this by storing the current directory in a variable, but that code seems needlessly complicated for what I imagine is a very common and simple task.
Is there a standard way to reliably call helper.sh
from within script.sh
? And will work in any Bash-supported operating system?
$0 is considered unsafe by many devs. I have found another solution, it is safe for a chain of bash scripts and source.
If a.sh needs to execute b.sh (which locates in the same folder) using child bash process:
If a.sh needs to execute b.sh (which locates in the same folder) using same bash process:
Since
$0
holds the full path of the script that is running, you can usedirname
against it to get the path of the script:so if you for example store it in
/tmp/a.sh
then you will see an output like:so
Using
dirname "$0"
will allow you to keep track of the original path.Again, since you have the path in
$0
you cancd
back to it.