4

I'm tying to write a script which uses variables declared in another script. I've tried so far using export to define environmental variables or just using local ones.

So I have my config script:

export DIR_STORAGE="/var/storage/"

And script trying to use it in the same directory:

source conf.sh
echo "DIR="${DIR_STORAGE}

but that doesn't seem to work. How can I fix this?

3
  • 5
    Works for me. What doesn't work? Commented Jul 23, 2012 at 9:22
  • don not forget to include shebangs in the beginning of your scirpts: #!/bin/bash -> en.wikipedia.org/wiki/Shebang_(Unix) Also try to specify full path to conf.sh (for testing). Commented Jul 23, 2012 at 9:25
  • Hm, it worked with absolute path, thanks. Although this doesn't look like an elegant solution. Commented Jul 23, 2012 at 9:43

1 Answer 1

5

Even if you have both files in the same directory, source conf.sh will look for conf.sh in the current directory. For example:

SHELL$ pwd
/home/user

SHELL$ ls mydir/
script.sh conf.sh

SHELL$ mydir/script.sh
script.sh: line 1: conf.sh: No such file or directory

In this case, the script will look for 'conf.sh' in the current (home) directory, not under mydir.

To avoid this and always look for the config file in the same directory where the script is, a common practice is to use:

source "$(dirname $0)/conf.sh"

This will extract the path from the command you used to invoke the script and append the config file name to it; in the example above, this will become source "mydir/conf.sh" which should work fine.

P.S. If you use source there's no need to export any variables.

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.