I have several individual bash scripts. They do different things, and are large (70-100 lines each). Thus I have kept them in separate files. But they are all related to a central problem and hence share several constant values in common.

So, for simplicity, I have ten constant variables, some are strings, some are numbers, while two are arrays, all of which need to be available throughout ten different bash scripts. How do I achieve this?

Note that while there is a central main.sh which can call these individual bash scripts, this won't always be the case. They can also be called directly from the command line (./script1.sh). Even in that case the variables should be made available to the scripts.

The only way I thought of was that to code in dev/script1.temp.sh files, and every time I need to run any file, I run a build.sh bash script that simply replaced (via grep) all occurrences of a particular constant ($CONSTANT) throughout the file to produce build/script1.sh.

  • You could either set them as environment variables so they are the same across every executed script, or keep them all in a file which you parse during the start of every script. Which solution do you prefer? I'd suggest environment variables. – Panki Jan 17 at 16:26

Put all the constants in a file, constants.env for example. And in all the scripts using any of those constants, put . constants.env to load them.

For example, constants.env:



. constants.env
echo $HELLO

Executing the example:

$ ./script.sh 

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.