如何在批处理脚本中“包含”数据文件?

时间:2012-04-22 06:06:46

标签: batch-file

我想在批处理脚本中“包含”一个数据文件。让我向您解释一下我将如何在Unix shell脚本中执行此操作,以便对我在批处理脚本中尝试实现的内容毫无疑问。

#!/bin/bash
. data.txt # Load a data file.

# Sourcing a file (dot-command) imports code into the script, appending to the script
# same effect as the #include directive in a C program).
# The net result is the same as if the "sourced" lines of code were physically present in the body of the script.
# This is useful in situations when multiple scripts use a common data file or function library.

# Now, reference some data from that file.
echo "variable1 (from data.txt) = $variable1"
echo "variable3 (from data.txt) = $variable3"

这是data.txt:

# This is a data file loaded by a script.
# Files of this type may contain variables, functions, etc.
# It may be loaded with a 'source' or '.' command by a shell script.
# Let's initialize some variables.
variable1=22
variable2=474
variable3=5
variable4=97
message1="Hello, how are you?"
message2="Enough for now. Goodbye."

在批处理脚本中,我的目的是在data.txt中设置环境变量,并在我将在后面创建的每个批处理脚本中“源”该文件。这也将帮助我通过修改一个文件(data.txt)而不是修改多个批处理脚本来更改环境变量。有任何想法吗?

2 个答案:

答案 0 :(得分:3)

最简单的方法是在data.bat文件中存储多个SET命令,然后可以由任何批处理脚本调用。例如,这是data.bat:

rem This is a data file loaded by a script.
rem Files of this type may contain variables and macros.
rem It may be loaded with a CALL THISFILE command by a Batch script.
rem Let's initialize some variables.
set variable1=22
set variable2=474
set variable3=5
set variable4=97
set message1="Hello, how are you?"
set message2="Enough for now. Goodbye."

要在任何脚本中“获取”此数据文件,请使用:

call data.bat

Adenddum :使用函数“包含”辅助(库)文件的方法。

使用“包含”文件的函数(子例程)并不像变量那么直接,但可以完成。要在批处理中执行此操作,您需要物理将data.bat文件插入到原始批处理文件中。当然,这可以通过文本编辑器完成!但它也可以通过一个名为source.bat的非常简单的批处理文件以自动方式实现:

@echo off
rem Combine the Batch file given in first param with the library file
copy %1+data.bat "%~N1_FULL.bat"
rem And run the full version
%~N1_FULL.bat%

例如,BASE.BAT:

@echo off
call :Initialize
echo variable1 (from data.bat) = %variable1%
echo variable3 (from data.bat) = %variable%
call :Display
rem IMPORTANT! This file MUST end with GOTO :EOF!
goto :EOF

DATA.BAT:

:Initialize
set variable1=22
set variable2=474
set variable3=5
set variable4=97
exit /B

:display
echo Hello, how are you?
echo Enough for now. Goodbye.
exit /B

您甚至可以使source.bat更复杂,因此它会检查基本文件和库文件的修改日期,并仅在需要时创建_FULL版本。

我希望它有所帮助...

答案 1 :(得分:1)

在DOS批处理文件中没有自动方法。您必须在循环中对文件进行标记。类似的东西:

 for /f "tokens=1,2 delims==" %i in (data.txt) do set %i=%j

当然,该行代码不会考虑示例data.txt文件中的注释行。