0

For example. I have 2 discrete scripts, which I want to remain and run separately. Script 1 utilizes a read function asking for a desired filename lets just say name1, does it's thing, and outputs the file with name1.

I need the second script to utilize name1 as part of an input, as well as a configuration file separate from the script that is able to point to name1 [assuming directory is fixed, but file name is variable.]

To do this, I imagine I'd need a way to export a global variable The way I have it now looks something like this:

read -p "What do you want this file to be called?: " name1
export name1=$name1

running the following as

. script1.sh

and then

echo $name1

yields the correct results, but how can I replicate this behaviour without having to specify run the script in the current shell with . - assuming that the next person would just run ./script1.sh or something, is there a way to export globally? This way I could use the variable $name1 in both the config file as well as script2.

Many thanks in advance.

2

You can't really. A script can not set an environment variable in the parent shell's environment.

One solution would obviously be to create a third script that runs the two other scripts in the particular way that they need to be run. It would source the first script and then run the second script.

Alternatively, combine the two scripts into one script. If you split them up to "keep things separate", then you can do the same with functions in one and the same script if you wish.

Also,

export name1=$name1

may be shortened to

export name1
  • thank you sir. originally I had combined them, but it seems script2 will be run multiple times while script1 only needs to be run once (but needs to happen before script2 can at all). I suppose I could have logic to skip to a particular portion in the script (e.g. a menu asking if you want to do part1 or part2's functionality.) I feel like there may be a more elegant solution however. – CharlieTango92 Apr 25 '18 at 17:05
  • so I'm thinking maybe the 3rd script idea is probably the more viable option, i'll begin to look into this. – CharlieTango92 Apr 25 '18 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.