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)而不是修改多个批处理脚本来更改环境变量。有任何想法吗?

4

2 回答 2

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

附录:“包含”具有功能的辅助(库)文件的方法。

使用“包含”文件的函数(子程序)不像变量那么直接,但可以做到。要在 Batch 中执行此操作,您需要将 data.bat 文件物理插入到原始 Batch 文件中。当然,这可以通过文本编辑器完成!但也可以借助一个非常简单的批处理文件 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

数据.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 版本。

我希望它有帮助...

于 2012-04-22T07:26:18.903 回答
1

在 DOS 批处理文件中没有自动执行此操作的方法。您必须循环标记文件。就像是:

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

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

于 2012-04-22T06:15:07.220 回答