How do you use SETLOCAL in a batch file?

后端 未结 3 1285
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 09:44

How do you use setlocal in a batch file? I am just learning scripting and would like it explained to me in very simple terms.

I have a script that stops

相关标签:
3条回答
  • 2020-12-16 10:37

    You make the first line SETLOCAL. This example is from the linked article below:

    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
    

    The most frequent use of SETLOCAL is to turn on command extensions and allow delayed expansion of variables:

    SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
    

    For more info on SETLOCAL see the Command Line Reference at Microsoft TechNet.

    Direct link to Setlocal

    0 讨论(0)
  • 2020-12-16 10:42

    Try this:

    SET PATH=%PATH%;%~dp0;

    This will get your local folder your are running the batch from and add it to the current path.

    example: if your are running a .bat or .cmd from d:\tools\mybatch.bat it will add d:\tools to the current path so that it may find additional files on that folder.

    0 讨论(0)
  • 2020-12-16 10:45

    Suppose this code:

    If "%getOption%" equ  "yes" (
       set /P option=Enter option: 
       echo Option read: %option%
    )
    

    Previous code will NOT work becase %option% value is replaced just one time when the IF command is parsed (before it is executed). You need to "delay" variable value expansion until SET /P command had modified variable value:

    setlocal EnableDelayedExpansion
    If "%getOption%" equ  "yes" (
       set /P option=Enter option: 
       echo Option read: !option!
    )
    

    Check this:

    set var=Before
    set var=After & echo Normal: %var%  Delayed: !var!
    

    Guess what the output is...

    0 讨论(0)
提交回复
热议问题