Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Both if and else block are executed in Batch script

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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"

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading