批处理文件包含变量的外部文件 [英] Batch file include external file for variables

查看:112
本文介绍了批处理文件包含变量的外部文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个批处理文件,我想包括含有一些变量(比如配置变量)的外部文件。这可能吗?

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

推荐答案

注意:我假设Windows批处理文件,大多数人似乎不知道有显著差异,只是一味地叫一切背景黑色DOS灰色文本。不过,第一个变种应在DOS下正常工作。

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.

要做到这一点IST只是把变量在批处理文件中自己最简单的方式,每个都有自己的设置语句:

The easiest way to do this ist to just put the variables in a batch file themselves, each with its own set statement:

set var1=value1
set var2=value2
...

和在你的主批次:

call config.cmd

当然,这也使得能够有条件地或根据系统的各方面创建的变量,所以它是pretty通用。然而,任意code能运行,且如果有语法错误,那么你的主批次将退出过。在UNIX世界中,这似乎是相当普遍,尤其是贝壳。如果你仔细想想, autoexec.bat文件是什么都没有。

另一种方法是配置文件中某种 VAR =值对:

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.

一般情况下,自动转义任意输入,不会导致头痛或问题,在批处理文件似乎pretty不可能给我。至少我没有找到一个方法来做到这一点呢。当然,第一个解决方案,你要推送的责任之一写入配置文件。

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.

这篇关于批处理文件包含变量的外部文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆