It can be useful to capture environment variable settings in a file. These files generally want to live with the project. This presents two problems when working with version control.
- The environment variable settings may contain sensitive information, like passwords.
- The environment variable settings may be specific to the local machine.
Both problems can be solved by commiting an example file with benign defaults instead of a file with sensitive or machine specific values. This post covers a specific strategy for doing this.
Create an environment.sh.example file template. This file provides the structure for storing environment variables, but contains benign default values that can be committed to version control. It also serves as a list of environment variables that need to be or ought to be defined. A real file may have more comments.
Note that the settings are printed at the end of the file. Using this strategy, a variable needs to manually be added to the list of values to print after it has been added. Username:password pairs are also printed, but the password is hidden. This is not really secure because anyone could cat the file, but it is suitable for some projects.
environment.sh.example complete listing
Add the real non-example environment.sh file to .gitignore. At this point the repository can be commited version control. Note that adding new environment varaibles generally requires updating both environment.sh.example with benign defaults and environment.sh with real working values.
.gitignore partial listing
To use this setup, copy environment.sh.example to environment.sh, customize it and then load the environment variables.
Output will look something like this.
Note that as written blank values are supposedly treated as default values. This functionality needs to exist where the environment variables are used. For example, in an sh script you can set a variable to a default value if it is not defined as follows.
some_script.sh partial listing