0

I've been working on a few scripts lately and I found that it would be really useful to separate some common functionalities on other files like 'utils' and the import them into my main scripts. For this, I used source ./utils.sh. However, It seems that this approach depends on the current path from where I'm calling my main script.

Let's say I have this folder structure:

scripts/
  |-tools/
  |  |-utils.sh
  |-main.sh

On main.sh:

source ./tools/utils.sh
some_function_defined_on_utils_sh
...

If I run main.sh from scripts/ folder everything works fine. But if I run it from a different directory ./scripts/main.sh the script fails because it can't find ./tools/utils.sh, which makes sense.

I understand why this doesn't work. My question is if there is any other mechanism to import 'modules' into my script, and make everything current-dir agnostic (just like python scripts from utils import some_function_defined_on_utils_sh))

Thanks!

1
  • Strictly speaking, no. The arguments to source are either absolute path names, relative (to the current working directory) path names, or filenames to be found via PATH lookup. Commented Oct 31, 2017 at 15:19

1 Answer 1

1

Define an environment variable with a suitable default setting that is where you'll store your modules, and then read the module using the . (dot) command.

One serious option is simply to place the files in a directory already on your PATH — $HOME/bin is a plausible candidate for private material; /usr/local/bin for material to be shared. Then you won't even need to specify the path to the files; you can write . file-found-on-path to read it. Of course, the downside is that if someone switches their PATH setting, or puts a file with the same name in another directory earlier on their PATH, then you end up with a mess. The files do not even need to be executable — they just need to be readable to be usable with the dot (.) command (or in Bash/C shells, the source command).

Or you could specify the location more exactly, such as:

. ${SHELL_UTILITY_DIR:-/opt/shell/bin}/tools/utils.sh

or something along those general lines. The choice of environment variable name and default location is up to you, and how much substructure you use on the directory is infinitely variable. Simplicity and consistency are paramount. (Also consider whether versioning will be a problem; how will you manage updates to your utilities?)

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

Comments

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.