这对我来说是一个有趣的话题!我想对此做一些观察。
重要的一点是:批处理文件是具有 .BAT 或 .CMD 扩展名的文件。时期。批处理文件除了执行常用的 DOS 命令外,还可以实现某些特定的批处理文件功能,特别是:
- 通过 %1 %2 ... 访问批处理文件参数并执行 SHIFT 命令。
- 执行 GOTO 命令。
- 执行 CALL :NAME 命令(内部子程序)。
- 执行 SETLOCAL/ENDLOCAL 命令。
现在有趣的部分是:任何文件都可以重定向为 CMD.exe 的输入,因此其中包含的 DOS 命令以类似于批处理文件的方式执行,但有一些区别。最重要的是以前的 批处理文件工具 将不起作用。下面的 NOT-Batch 文件(我称之为 BATCH.TXT)说明了另一个区别:
@echo off
rem Echo off just suppress echoing of the prompt and each loop of FOR command
rem but it does NOT suppress the listing of these commands!
rem Pause command does NOT pause, because it takes the character that follows it
pause
X
rem This behavior allows to put data for a SET /P command after it
set /P var=Enter data:
This is the data for previous command!
echo Data read: "%var%"
rem Complex FOR/IF commands may be assembled and they execute in the usual way:
for /L %i in (1,1,5) do (
set /P line=
if "!line:~0,6!" equ "SHOW: " echo Line read: !line:~6!
)
NOSHOW: First line read
SHOW: Second line
NOSHOW: This is third line
SHOW: The line number 4
NOSHOW: Final line, number five
rem You may suppress the tracing of the execution redirecting CMD output to NUL
rem In this case, redirect output to STDERR to display messages in the screen
echo This is a message redirected to STDERR >&2
rem GOTO command doesn't work:
goto label
goto :EOF
rem but both EXIT and EXIT /B commands works:
exit /B
:label
echo Never reach this point...
要执行前一个文件,输入:CMD /V:ON
更具体的差异与 NOT-Batch 文件中的命令在 命令行上下文而非批处理文件上下文中执行的事实有关。也许 Dave 或 jeb 可以详细说明这一点。
编辑: 补充意见 (batch2.txt):
@echo off
rem You may force SET /P command to read the line from keyboard instead of
rem from following lines by redirecting its input to CON device.
rem You may also use CON device to force commands output to console (screen),
rem this is easier to write and read than >&2
echo Standard input/output operations> CON
echo/> CON
< CON set /P var=Enter value: > CON
echo/> CON
echo The value read is: "%var%"> CON
以这种方式执行上一个文件:CMD NUL
编辑:更多额外观察 (batch3.txt)
@echo off
rem Dynamic access to variables that usually requires DelayedExpansion via "call" trick
rem Read the next four lines; "next" means placed after the FOR command
rem (this may be used to simulate a Unix "here doc")
for /L %i in (1,1,4) do (
set /P line[%i]=
)
Line one of immediate data
This is second line
The third one
And the fourth and last one...
(
echo Show the elements of the array read:
echo/
for /L %i in (1,1,4) do call echo Line %i- %line[%i]%
) > CON
按常规方式执行这个文件:CMD NUL
有趣!不是吗?
编辑:现在,可以在 NotBatch.txt 文件中模拟 GOTO 和 CALL 命令!!!见this post。
安东尼奥