I have a batch file and I want to include an external file containing some variables (say configuration variables). Is it possible?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Note: 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
setstatement:and in your main batch:
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.batis nothing else.Key/value pairs
Another way would be some kind of
var=valuepairs in the configuration file:You can then use the following snippet to load them:
This utilizes a similar trick as before, namely just using
seton 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.