0

I have a script like this:

#!/bin/bash

. config

./sub-script

There are a lot of variables in config and I don't want to pass them to sub-scirpt like ./subscript arg1 arg2 ... arg100500.
Also, I don't like an idea to source config from sub-script, because in general it may not know where there config file resides.

Is there any other way to make config available in sub-script?

4
  • @the_velour_fog, but they don't. Just checked it. Apr 26, 2016 at 10:13
  • What about if you just use source /path/to/sub-script ? can you try that? Apr 26, 2016 at 10:14
  • @the_velour_fog, that way it works, thanks. Apr 26, 2016 at 10:15
  • You could pass the full pathname of the config file to the sub-script, e.g. ./sub-script /path/to/config. the sub-script could then do something like cfg="$1" ; shift ; . "$cfg".
    – cas
    Apr 26, 2016 at 12:02

3 Answers 3

3

If you can set your script up this way

#!/bin/bash

. config

. /path/to/sub-script

Any variables initialised in config should become available to the main script and any scripts it sources.

Explanation

It seems your script was launching a new non-interactive shell process, shell variables initialised in the parent script would not have been available - but exported environment variables should be available to the new child process.

2

You can export your variables:

 VAR=foo
 export VAR

or:

 export VAR=foo

However, these variables will be visible in the environment of all subprocesses.

1
  • that is what I was looking for. thnx Apr 26, 2016 at 10:19
0

You could pass the full pathname of the config file to the sub-script. For example:

#!/bin/bash

. ./config

./sub-script ./config

The sub-script could then do something like this:

cfg="$1"
shift
. "$cfg"

You could even have a default for $cfg, just in case $1 is empty.

cfg=${1:-/path/to/default/config}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .