1

バッチスクリプトにデータファイルを「含め」たい。私がバッチスクリプトで何を達成しようとしているのかについて疑いの余地がないように、Unixシェルスクリプトでそれをどのように行うかについて説明しましょう。

#!/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に環境変数を設定し、後で作成する各バッチスクリプトでそのファイルを「ソース」することを目的としています。これは、複数のバッチスクリプトを変更する代わりに、1つのファイル(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

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バージョンを作成します。

お役に立てば幸いです...

于 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 に答える