.* Relative paths are ALWAYS resolved from where the script is run.
.* Not from the path of script file. Not from th path of sourced scripts, if any.
.* The absolute path of the folder where the current script is given by
"$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
.* Sourced scripts will have access to the variables declared in the parent script.
Create a hierarchy: /tmp/nepal.sh /tmp/nepal.txt /tmp/nepal/ /tmp/nepal/state.sh /tmp/nepal/state.txt /tmp/tmp.txt
- /tmp/nepal.txt
- /tmp/nepal/state.txt
- /tmp/tmp.txt
###Dummy file: /tmp/nepal.txt
I am nepal.txt
###Dummy file: /tmp/nepal/state.txt
I am state.txt
###Dummy file: /tmp/tmp.txt
I am tmp.txt
###Create a test file
#!/bin/bash
echo "script run from $(pwd)"
COUNTRY="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "I am nepal.sh, residing in $COUNTRY"
#source ./nepal/state.sh # only works if this script is run from inside /country
source $COUNTRY/nepal/saate.sh # works no matter where the script is run from.
- /tmp/nepal/state.sh
#!/bin/bash
echo "parent is $COUNTRY"
STATE="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "I am state.sh residing in $STATE"
cp $COUNTRY/deletethis.txt deletedthis.txt
Run the test by running the file /tmp/country/nepal.sh from different locations.
cd ~; /tmp/country/nepal.sh
cd /; bash /tmp/country/nepal.sh
cd /; /tmp/country/nepal.sh
cd /tmp; ./country/nepal.sh
cd /tmp/nepal; ./nepal.sh
cd /tmp/nepal/state; ../nepal.sh