1

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.

1
  • 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, 2019 at 16:26

1 Answer 1

4

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:

HELLO=world

script.sh

#!/bin/bash
. constants.env
echo $HELLO

Executing the example:

$ ./script.sh 
world
0

You must log in to answer this question.

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