2

I am not trying to execute a Bash script from any directory by adding the script to my Path variable.

I want to be able to execute the script from any directory using the directory path to that file ... but the file I want to execute sources other files, that is the problem.

If I am in directory file with two scripts myFunctions.sh and sourceFunctions.sh

sourceFunctions.sh

#!/bin/bash
source ./myFunctions.sh
echoFoo

myFunctions.sh

function echoFoo()
{
    echo "foo"
}

I can run myFunctions.sh and foo will print to console, but If I go up a directory and run myFunctions.sh I get error

cd ..
file/sourceFunctions.sh
-bash: doFoo.sh: command not found

Unless I changed source file/myFunctions.sh to source file/myFunctions.sh in sourceFunctions.sh.

So how can I source independent of my working directory so I can run sourceFunctions.sh from any working directory I want?

Thanks

the_prole
  • 8,275
  • 16
  • 78
  • 163
  • Possible duplicate of [Add a bash script to path](https://stackoverflow.com/questions/20054538/add-a-bash-script-to-path) – grooveplex Feb 21 '19 at 00:13
  • how is this a duplicate? im not trying to add a bash script to a path variable – the_prole Feb 21 '19 at 00:14
  • Maybe something along the lines adding *`pwd`* to the source command? Maybe pwd does not work, but $BASH_SOURCE does https://unix.stackexchange.com/questions/4650/determining-path-to-sourced-shell-script ? – carlosvalderrama Feb 21 '19 at 00:22
  • I added an answer, maybe not the optimal, but it works – the_prole Feb 21 '19 at 00:23

2 Answers2

2

You have the right idea. Doesn't need to be that complicated though:

source `dirname $0`/myFunctions.sh

I often compute "HERE" at the top of my script:

HERE=`dirname $0`

and then use it as needed in my script:

source $HERE/myFunctions.sh

One thing to be careful about is that $HERE will often be a relative path. In fact, it will be whatever path you actually used to run the script, or "." if you provided no path. So if you "cd" within your script, $HERE will no longer be valid. If this is a problem, there's a way (can't think of it off hand) to make sure $HERE is always an absolute path.

0

I ended up just using a variable of the directory path to the script itself for the source directory

so

#!/bin/bash
source ./myFunctions.sh
echoFoo

becomes

#!/bin/bash
SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
source ${SCRIPTPATH}/myFunctions.sh
echoFoo

source

the_prole
  • 8,275
  • 16
  • 78
  • 163
  • This solution is more complicated than the solution above using "dirname". Is there a situation where this solution should be prefered? – Ernie Mur Sep 02 '20 at 10:10