Skip to content

Instantly share code, notes, and snippets.

@njsubedi
Last active June 3, 2019 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save njsubedi/991cb89fb5d8b2dc9a4b0ca440953c3d to your computer and use it in GitHub Desktop.
Save njsubedi/991cb89fb5d8b2dc9a4b0ca440953c3d to your computer and use it in GitHub Desktop.

Rules

.* 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.

Testing (These are the final files necessary)

Create a hierarchy: /tmp/nepal.sh /tmp/nepal.txt /tmp/nepal/ /tmp/nepal/state.sh /tmp/nepal/state.txt /tmp/tmp.txt

Create three dummy files

  • /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

/tmp/nepal.sh

#!/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.

Create the file that is being sourced the previous file:

  • /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 Tests

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment