2012-04-22 60 views
1

我想在批处理脚本中“包含”一个数据文件。让我来解释一下,我将如何在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)而不是修改多个批处理脚本来更改环境变量。有任何想法吗?

回答

3

最简单的方法是将多个SET命令存储在data.bat文件中,然后由任何批处理脚本调用该命令。例如,这是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文件插入到原始批处理文件中。当然,这可以用文本编辑器完成!

@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:

但它也可以自动的方式有一个非常简单的批处理文件名为source.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版本。

我希望它有帮助...

+0

+1。谢谢。是否可以在data.bat中定义函数,以便这些函数可用于调用data.bat的脚本? – 2012-04-22 15:34:23

+0

@SachinS:见我的答案中的附录... – Aacini 2012-04-25 02:32:11

+0

谢谢。这真的很好。 – 2012-04-26 13:16:28

1

在DOS批处理文件中没有自动的方法。您必须在循环中标记文件。例如:

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

当然,该行代码并未考虑样本data.txt文件中的注释行。

相关问题