When you are using scripts to automate your builds (which you should do), you most probably want to keep the definition of your environment variables in an external file.
For example, in our builds, we are using multiple versions of Xcode and therefor need to set the proper DEVELOPER_DIR
environment variable.
You can store these in a file as follows:
.env
1DEVELOPER_DIR=/Applications/Xcode-v12.1.app/Contents/Developer
If you are using plain shell scripts, loading the variables is easy:
1source .env
2echo $DEVELOPER_DIR
To load them into a Makefile, you can use the following trick:
Makefile
1include .env
2export
3
4build:
5 @echo $(DEVELOPER_DIR)
Since we have some older build scripts which are based on Apache Ant, you can use the same file in Apache Ant by using the loadproperties
task:
1<?xml version="1.0" encoding="UTF-8"?>
2<project name="builder" default="init" basedir=".">
3 <target name="init">
4 <loadproperties srcFile=".env" />
5 <echo message="${DEVELOPER_DIR}" />
6 </target>
7</project>
If you want to read them from Python, you can do:
1import os
2
3def read_properties_from_file(path):
4 return dict(l.rstrip().split('=', maxsplit=1) for l in open(path) if not l.startswith("#"))
5
6def load_env_vars_from_properties_file(path):
7 props = read_properties_from_file(path)
8 for k, v in props.items():
9 os.environ[k] = v
10
11def main():
12 load_env_vars_from_properties_file(".env")
13 print(os.environ.get("DEVELOPER_DIR")
14
15if __name__ == '__main__':
16 main()
Voila, a neat way to have all your build scripts share the same environment variables.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.