[batch-file] 배치 파일에는 변수에 대한 외부 파일이 포함됩니다.

배치 파일이 있고 일부 변수 (예 : 구성 변수)를 포함하는 외부 파일을 포함하고 싶습니다. 가능할까요?



답변

참고 : 대부분의 사람들이 중요한 차이점을 인식하지 못하고 검정색 배경의 DOS에 회색 텍스트로 모든 것을 맹목적으로 호출하는 것처럼 보이기 때문에 Windows 배치 파일을 가정하고 있습니다. 그럼에도 불구하고 첫 번째 변종은 DOS에서도 작동합니다.

실행 가능한 구성

이 작업을 수행하는 가장 쉬운 방법은 각각 고유 한 set명령문이 있는 배치 파일 자체에 변수를 넣는 것입니다 .

set var1=value1
set var2=value2
...

그리고 메인 배치에서 :

call config.cmd

물론 조건부로 또는 시스템의 측면에 따라 변수를 생성 할 수도 있으므로 매우 다양합니다. 그러나 여기에서 임의의 코드를 실행할 수 있으며 구문 오류가 있으면 기본 배치도 종료됩니다. UNIX 세계에서 이것은 특히 셸에서 매우 일반적으로 보입니다. 그리고 그것에 대해 생각한다면, autoexec.bat다른 것은 없습니다.

키 / 값 쌍

또 다른 방법은 var=value구성 파일에서 일종의 쌍입니다.

var1=value1
var2=value2
...

그런 다음 다음 스 니펫을 사용하여로드 할 수 있습니다.

for /f "delims=" %%x in (config.txt) do (set "%%x")

이것은 이전과 유사한 트릭을 사용 set합니다. 즉, 각 라인에서 사용 합니다. 따옴표가 같은 것들을 탈출있다 <, >, &, |. 그러나 입력에 따옴표가 사용되면 자체적으로 중단됩니다. 또한 이러한 문자로 저장된 변수의 데이터를 추가로 처리 할 때 항상주의해야합니다.

일반적으로 배치 파일에서 두통이나 문제를 일으키지 않도록 임의의 입력을 자동으로 이스케이프하는 것은 나에게 꽤 불가능 해 보입니다. 적어도 나는 그렇게 할 방법을 아직 찾지 못했습니다. 물론 첫 번째 솔루션을 사용하면 구성 파일을 작성하는 사람에게 해당 책임을 부여합니다.


답변

외부 구성 파일도 유효한 배치 파일 인 경우 다음을 사용할 수 있습니다.

call externalconfig.bat

스크립트 내부. 다음 a.bat를 만들어보십시오.

@echo off
call b.bat
echo %MYVAR%

및 b.bat :

set MYVAR=test

a.bat를 실행하면 출력이 생성됩니다.

test


답변

Batch는 입력 및 출력 파이프로보다 작음 및보다 큼 대괄호를 사용합니다.

>file.ext

위와 같이 하나의 출력 대괄호 만 사용하면 해당 파일의 모든 정보를 덮어 씁니다.

>>file.ext

이중 오른쪽 대괄호를 사용하면 파일에 다음 줄이 추가됩니다.

(
echo
echo
)<file.ext

이것은 파일의 행을 기반으로 매개 변수를 실행합니다. 이 경우 “echo”를 사용하여 입력 할 두 줄을 사용합니다. 오른쪽 괄호 괄호에 닿는 왼쪽 괄호는 해당 파일의 정보가 해당 행으로 파이프된다는 것을 의미합니다.

예제 전용 읽기 / 쓰기 파일을 컴파일했습니다. 다음은 각 부분이 수행하는 작업을 설명하기 위해 섹션으로 나누어 진 파일입니다.

@echo off
echo TEST R/W
set SRU=0

이 예에서 SRU는 무엇이든 될 수 있습니다. Enter 키를 너무 빨리 누르면 충돌을 방지하기 위해 실제로 설정하고 있습니다.

set /p SRU=Skip Save? (y):
if %SRU%==y goto read
set input=1
set input2=2
set /p input=INPUT:
set /p input2=INPUT2:

이제 변수를 파일에 써야합니다.

(echo %input%)> settings.cdb
(echo %input2%)>> settings.cdb
pause

.cdb를 “명령 데이터베이스”의 약식으로 사용합니다. 모든 확장을 사용할 수 있습니다. 다음 섹션은 코드를 처음부터 테스트하는 것입니다. 우리는 파일의 시작 부분에서 실행 된 set 변수를 사용하지 않고 방금 작성한 settings.cdb에서로드하기를 원합니다.

:read
(
set /p input=
set /p input2=
)<settings.cdb

그래서 우리는 input과 input2의 변수를 설정하기 위해 파일의 시작 부분에 작성한 정보의 처음 두 줄을 파이프했습니다.

echo %input%
echo %input2%
pause
if %input%==1 goto newecho
pause
exit

:newecho
echo If you can see this, good job!
pause
exit

settings.cdb가 괄호 안에 파이프되는 동안 설정된 정보가 표시됩니다. 좋은 직업 동기 부 여자로서 Enter를 누르고 이전에 “1”로 설정 한 기본값을 설정하면 좋은 직업 메시지가 반환됩니다. 브래킷 파이프를 사용하는 것은 양방향으로 진행되며 “FOR”항목을 설정하는 것보다 훨씬 쉽습니다. 🙂


답변

따라서이 작업을 올바르게 수행해야합니까? :

@echo off
echo text shizzle
echo.
echo pause^>nul (press enter)
pause>nul

REM writing to file
(
echo XD
echo LOL
)>settings.cdb
cls

REM setting the variables out of the file
(
set /p input=
set /p input2=
)<settings.cdb
cls

REM echo'ing the variables
echo variables:
echo %input%
echo %input2%
pause>nul

if %input%==XD goto newecho
DEL settings.cdb
exit

:newecho
cls
echo If you can see this, good job!
DEL settings.cdb
pause>nul
exit


답변

:: savevars.bat
:: Use $ to prefix any important variable to save it for future runs.

@ECHO OFF
SETLOCAL

REM Load variables
IF EXIST config.txt FOR /F "delims=" %%A IN (config.txt) DO SET "%%A"

REM Change variables
IF NOT DEFINED $RunCount (
    SET $RunCount=1
) ELSE SET /A $RunCount+=1

REM Display variables
SET $

REM Save variables
SET $>config.txt

ENDLOCAL
PAUSE
EXIT /B

산출:

$ RunCount = 1

$ RunCount = 2

$ RunCount = 3

위에 설명 된 기술을 사용하여 여러 배치 파일간에 변수를 공유 할 수도 있습니다.

출처 : http://www.incodesystems.com/products/batchfi1.htm


답변

약간 오래된 주제이지만 며칠 전에 같은 질문이 있었고 다른 아이디어가 떠 올랐습니다 (아마도 누군가가 여전히 유용하다고 생각할 것입니다)

예를 들어 다양한 주제 (가족, 크기, 색상, 동물)로 config.bat를 만들고 배치 스크립트에서 원하는 순서대로 개별적으로 적용 할 수 있습니다.

@echo off
rem Empty the variable to be ready for label config_all
set config_all_selected=

rem Go to the label with the parameter you selected
goto :config_%1

REM This next line is just to go to end of file
REM in case that the parameter %1 is not set
goto :end

REM next label is to jump here and get all variables to be set
:config_all
set config_all_selected=1


:config_family
set mother=Mary
set father=John
set sister=Anna
rem This next line is to skip going to end if config_all label was selected as parameter
if not "%config_all_selected%"=="1" goto :end

:config_test
set "test_parameter_all=2nd set: The 'all' parameter WAS used before this echo"
if not "%config_all_selected%"=="1" goto :end

:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end


:config_color
set first_color=blue
set second_color=green
if not "%config_all_selected%"=="1" goto :end


:config_animals
set dog=Max
set cat=Miau
if not "%config_all_selected%"=="1" goto :end


:end

그 후에는 ‘call config.bat all’로 완전히 호출하거나 일부만 호출하여 어디에서나 사용할 수 있습니다 (아래 예제 참조). 여기에있는 아이디어는 모든 것을 한번. 일부 변수는 아직 호출하고 싶지 않아 나중에 호출 할 수 있습니다.

예제 test.bat

@echo off

rem This is added just to test the all parameter
set "test_parameter_all=1st set: The 'all' parameter was NOT used before this echo"

call config.bat size

echo My birthday present had a width of %width% and a height of %height%

call config.bat family
call config.bat animals

echo Yesterday %father% and %mother% surprised %sister% with a cat named %cat%
echo Her brother wanted the dog %dog%

rem This shows you if the 'all' parameter was or not used (just for testing)
echo %test_parameter_all%

call config.bat color

echo His lucky color is %first_color% even if %second_color% is also nice.

echo.
pause

다른 사람들이 여기에서 그들의 대답으로 나를 돕는 방식을 돕길 바랍니다.

위의 짧은 버전 :

config.bat

@echo off
set config_all_selected=
goto :config_%1
goto :end

:config_all
set config_all_selected=1

:config_family
set mother=Mary
set father=John
set daughter=Anna
if not "%config_all_selected%"=="1" goto :end

:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end

:end

test.bat

@echo off

call config.bat size
echo My birthday present had a width of %width% and a height of %height%

call config.bat family
echo %father% and %mother% have a daughter named %daughter%

echo.
pause

좋은 날.


답변

좋은 오래된 매개 변수를 잊지 말자. * .bat 또는 * .cmd 파일을 시작할 때 명령 파일 이름 뒤에 최대 9 개의 매개 변수를 추가 할 수 있습니다.

call myscript.bat \\path\to\my\file.ext type
call myscript.bat \\path\to\my\file.ext "Del /F"

예제 스크립트

myscript.bat는 다음과 같을 수 있습니다.

@Echo Off
Echo The path of this scriptfile %~0
Echo The name of this scriptfile %~n0
Echo The extension of this scriptfile %~x0
Echo.
If "%~2"=="" (
   Echo Parameter missing, quitting.
   GoTo :EOF
)
If Not Exist "%~1" (
   Echo File does not exist, quitting.
   GoTo :EOF
)
Echo Going to %~2 this file: %~1
%~2 "%~1"
If %errorlevel%  NEQ 0 (
   Echo Failed to %~2 the %~1.
)
@Echo On

예제 출력

c:\>c:\bats\myscript.bat \\server\path\x.txt type
The path of this scriptfile c:\bats\myscript.bat
The name of this scriptfile myscript
The extension of this scriptfile .bat

Going to type this file: \\server\path\x.txt
This is the content of the file:
Some alphabets: ABCDEFG abcdefg
Some numbers: 1234567890

c:\>c:\bats\myscript.bat \\server\path\x.txt "del /f "
The path of this scriptfile c:\bats\myscript.bat
The name of this scriptfile myscript
The extension of this scriptfile .bat

Going to del /f  this file: \\server\path\x.txt

c:\>