0

I am trying to write a batch script which checks for the presence of environment variable MY_VAR and if Not set then it tries to get hold of the 1st argument passed to the script. It then removes it quotes if present (") and then removes the trailing slash (/).

I have enabled extensions via setlocal ENABLEEXTENSIONS as my env variable MY_VAR can have spaces in its value and hence in order to use IF with DEFINED i need to enable extensions.

However, my whole program seems to not behave properly.

@echo off

cd %~dp0

setlocal ENABLEEXTENSIONS

@REM if MY_VAR Is defined then it can have spaces

if not defined MY_VAR ( 
    IF [%1] == [] goto :doSomething

    set ARG1=%1
    echo "Script is invoked with argument %ARG1%"
    set ARG1=%ARG1:"=%  
    
    :doSomething
    echo "I will do something"

    IF [%1]==[] (
        echo "Do  more things1"
    ) ELSE (
        echo "Do  more things2"
    )
)
else (
    IF [%1]==[] (
        echo "Do  more things3"
    ) ELSE (
        echo "Do  more things4"
    )
)
endlocal

I am invoking this as below

C:\>cmd /c call "C:\mydir\test2.bat" "c:\myDir sgds\"

The output is as below

"ARG1 is set to  "
"I will do something"
"Do  more things2"

Why ARG1 is NOT set properly by below code lines?

set ARG1=%1
echo "ARG1 is set to  %ARG1%"
Helena
  • 444
  • 2
  • 15
  • 1
    Labels cannot appear in a block statement `(a parenthesised series of statements) – Magoo Jan 09 '23 at 10:21
  • @Magoo : Did you try running my code? It doesn't complain about any label. – Helena Jan 09 '23 at 10:25
  • 1
    No - it won't complain. The label breaks the `for` loop. `cmd` then continues to the line after the label (if/else in uppercase), ignores the `)` and then complains about the `else`. – Magoo Jan 09 '23 at 10:31
  • @Magoo : can you see the updated code? I am not clear why ARG1 isn't set properly. Doesn't look like the label is the culprit. Can you have a look? – Helena Jan 09 '23 at 10:35

1 Answers1

1
@ECHO OFF
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION 

REM if MY_VAR Is defined then it can have spaces

SET "arg1=%1"

if defined MY_VAR ( 
   IF [%1]==[] (
       echo "Do  more things3"
   ) ELSE (
       echo "Do  more things4"
   )
) ELSE (
 echo "Script is invoked with argument %ARG1%"
 IF DEFINED arg1 (
  set "ARG1=%ARG1:"=%"
  ECHO quotes are removed ARG1="!arg1!"
  IF "!arg1:~-1!"=="/" SET "ARG1=!arg1:~0,-1!"
  ECHO with terminal slash removed ARG1="!arg1!"
 )
 echo "I will do something with "!arg1!"
)
ENDLOCAL

GOTO :EOF

Beware of the delayed expansion trap

Note the use of !var! after invoking enabledelayedexpansion. %var% within a code block will be resolved to the value of var when the code block is encountered. !var! (after invoking enabledelayedexpansion) will be resolved to the value of var as it is changed within the block.

Magoo
  • 77,302
  • 8
  • 62
  • 84