1

I am new to Batch scripting. I am trying to write a script which parses given command and check if argument with name 'folder 'is present in that command and if not , add that argument with default value.

I have written following script. This scripts executes correctly if argument is missing. But if argument is present , both if and else blocks are executed.

Please help. Thanks in advance.

@echo off

set ARGS=-action generate -folder "Source"
set t=%ARGS%

echo %t%|find "-folder" >nul
if errorlevel 1 (
    goto setDefaultFolder
) else (
    echo Folder is specified in command
)

:setDefaultFolder
echo Folder is NOT specified in command. User's current directory will be used as Folder.
set folderArgName=-folder
set folderArgValue="%cd%"
set folderArg=%folderArgName% %folderArgValue%
echo folderArgName : %folderArgName%
echo folderArgValue : %folderArgValue%
echo folderArg: %folderArg%
set ARGS=%ARGS% %folderArg%
echo ARGS : %ARGS%

Output of code :

Folder is specified in command
Folder is NOT specified in command. User's current directory will be used as Folder.
folderArgName : -folder
folderArgValue : "C:\work"
folderArg: -folder "C:\work"
ARGS : -action generate -folder "Source" -folder "C:\work"
1
  • 2
    Batch scripts are executed line by line. The else should not execute on the if being true, however the label setdefaultfolder will execute even if the if condition is false unless you implement a sctipt break prior to the label. Commented Feb 22, 2022 at 9:49

1 Answer 1

3

You have to have a goto in the else, that goes to after the setDeafultFolder, otherwise it just will execute the setDefaultFolder after it

@echo off

set ARGS=-action generate -folder "Source"
set t=%ARGS%

echo %t%|find "-folder" >nul
if errorlevel 1 (
    goto setDefaultFolder
) else (
    echo Folder is specified in command
    goto endOfBatch
)

:setDefaultFolder
echo Folder is NOT specified in command. User's current directory will be used as Folder.
set folderArgName=-folder
set folderArgValue="%cd%"
set folderArg=%folderArgName% %folderArgValue%
echo folderArgName : %folderArgName%
echo folderArgValue : %folderArgValue%
echo folderArg: %folderArg%
set ARGS=%ARGS% %folderArg%
echo ARGS : %ARGS%

:endOfBatch
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.