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

4
  • Possible duplicate of Add a bash script to path Commented Feb 21, 2019 at 0:13
  • how is this a duplicate? im not trying to add a bash script to a path variable Commented Feb 21, 2019 at 0:14
  • Maybe something along the lines adding pwd to the source command? Maybe pwd does not work, but $BASH_SOURCE does unix.stackexchange.com/questions/4650/… ? Commented Feb 21, 2019 at 0:22
  • I added an answer, maybe not the optimal, but it works Commented Feb 21, 2019 at 0:23

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This solution is more complicated than the solution above using "dirname". Is there a situation where this solution should be prefered?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.