Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file include external file for variables

I have a batch file and I want to include an external file containing some variables (say configuration variables). Is it possible?

like image 724
Pablo Avatar asked May 04 '10 08:05

Pablo


People also ask

Can a batch file prompt for input?

You are able to prompt a user for input using a Batch script function.

What does %1 mean in a batch file?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.

What does && do in batch file?

&& runs the second command on the line when the first command comes back successfully (i.e. errorlevel == 0 ). The opposite of && is || , which runs the second command when the first command is unsuccessful (i.e. errorlevel != 0 ).


2 Answers

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 set statement:

set var1=value1 set var2=value2 ... 

and in your main batch:

call config.cmd 

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:

var1=value1 var2=value2 ... 

You can then use the following snippet to load them:

for /f "delims=" %%x in (config.txt) do (set "%%x") 

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.

like image 61
Joey Avatar answered Sep 21 '22 08:09

Joey


If the external configuration file is also valid batch file, you can just use:

call externalconfig.bat 

inside your script. Try creating following a.bat:

@echo off call b.bat echo %MYVAR% 

and b.bat:

set MYVAR=test 

Running a.bat should generate output:

test 
like image 43
chalup Avatar answered Sep 18 '22 08:09

chalup