如何在批处理文件中使用setlocal
?我正在学习脚本编写,需要通俗易懂地解释。
我的一个脚本会停止并显示< was unexpected at this time
,这可能与脚本中没有任何setlocal
语句有关。
如何在批处理文件中使用setlocal
?我正在学习脚本编写,需要通俗易懂地解释。
我的一个脚本会停止并显示< was unexpected at this time
,这可能与脚本中没有任何setlocal
语句有关。
你需要将第一行改为SETLOCAL
。这个例子来自下面链接的文章:
rem *******Begin Comment**************
rem This program starts the superapp batch program on the network,
rem directs the output to a file, and displays the file
rem in Notepad.
rem *******End Comment**************
@echo off
setlocal
path=g:\programs\superapp;%path%
call superapp>c:\superapp.out
endlocal
start notepad c:\superapp.out
SETLOCAL
的最常见用途是开启命令扩展并允许变量的延迟扩展:
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
想要了解更多关于SETLOCAL
的信息,请参考微软TechNet上的命令行参考。
Setlocal的直接链接。
假设这段代码:
If "%getOption%" equ "yes" (
set /P option=Enter option:
echo Option read: %option%
)
之前的代码不起作用,因为%option%值只会被替换一次,当IF命令被解析(在执行之前)时。你需要“延迟”变量值的扩展,直到SET /P命令修改了变量值:
setlocal EnableDelayedExpansion
If "%getOption%" equ "yes" (
set /P option=Enter option:
echo Option read: !option!
)
请检查:
set var=Before
set var=After & echo Normal: %var% Delayed: !var!
猜猜输出结果是什么...
尝试这个:
SET PATH=%PATH%;%~dp0;
这将获取您正在运行批处理文件的本地文件夹,并将其添加到当前路径中。
例如:如果您从d:\tools\mybatch.bat
运行.bat
或.cmd
,它将添加d:\tools
到当前路径中,以便可以在该文件夹中找到其他文件。
PATH
变量中,但需要多次运行脚本,则可以像示例中那样进行设置。此外,您不需要在脚本之后清理环境。也就是说,在您设置任何内容之前调用setlocal
,您可以使Windows shell脚本的行为类似于Bash脚本(不能更改父shell的环境)。 - Tomasz Gandorsetlocal
命令也会将任何目录更改设置为本地目录!这意味着在执行完命令后,您将返回到原始目录。 - Dylan Watson