Batch file include external file for variables
How to make a batch file to include an external file containing some variables (say configuration variables).
ote: I’m assuming Windows batch files as most people seem to be unaware that there are significant differences and just blindly call everything with grey text on black background DOS. Nevertheless, the first variant should work in DOS as well.
Executable configuration
The easiest way to do this is to just put the variables in a batch file themselves, each with its own set statement:
1 |
|
and in your main batch:
1 |
|
Of course, that also enables variables to be created conditionally or depending on aspects of the system, so it’s pretty versatile. However, arbitrary code can run there and if there is a syntax error, then your main batch will exit too. In the UNIX world this seems to be fairly common, especially for shells. And if you think about it, autoexec.bat is nothing else.
Key/value pairs
Another way would be some kind of var=value pairs in the configuration file:
1 |
|
You can then use the following snippet to load them:
1 |
|
This utilizes a similar trick as before, namely just using set on each line. The quotes are there to escape things like <
, >
, &
, |
. However, they will themselves break when quotes are used in the input. Also you always need to be careful when further processing data in variables stored with such characters.
Generally, automatically escaping arbitrary input to cause no headaches or problems in batch files seems pretty impossible to me. At least I didn’t find a way to do so yet. Of course, with the first solution you’re pushing that responsibility to the one writing the config file.
Reference
- Batch file include external file for variables: https://stackoverflow.com/questions/2763875/batch-file-include-external-file-for-variables