How to parse command line arguments with SWITCH in BATCH file - batch-file

We are trying to make a switch statement which is parsing command line argument in a batch file.
mybatch.bat -a 10 -b name -c India --zipcode 20
Only -a, -b, -c are parsing parameter (which is starts with -).
Our code will be like:
for %%x in (%*) do (
switch(%%x) (
case a:
SET first_number=%arg%
break
case b:
SET name=%arg%
case c:
for %%x in (%*) do (
SET place =%place% %arg%
)
default:
echo wrong parameter
)

The Batch file below parses all arguments that start with - and creates a series of variables that start with "option" and the names and values of all options given:
#echo off
setlocal EnableDelayedExpansion
set "option="
for %%a in (%*) do (
if not defined option (
set arg=%%a
if "!arg:~0,1!" equ "-" set "option=!arg!"
) else (
set "option!option!=%%a"
set "option="
)
)
SET option
For example:
>test -a 10 -b name -c India --zipcode 20
option--zipcode=20
option-a=10
option-b=name
option-c=India
This way, you need to make no changes in the parsing code if you want to add/change/delete any option, just use the value of the option you want. For example:
if defined option-x (
echo Option -x given: "%option-x%"
) else (
echo Option -x not given
)

Normally you try to keep things simple and have a set order for the parameters. To handle parameters in any, random order is a lot more effort than just knowing that %1 = number, %2 = name and %3 onwards = place.
That said, here's an attempt at a solution. I'm ignoring --params in the place section, just joining the values together.
#echo off
setlocal
:loop
if x%1 equ x goto done
set param=%1
if %param:~0,1% equ - goto checkParam
:paramError
echo Parameter error: %1
:next
shift /1
goto loop
:checkParam
if "%1" equ "-a" goto A
if "%1" equ "-b" goto B
if "%1" equ "-c" goto C
goto paramError
:A
shift /1
set first_number=%1
goto next
:B
shift /1
set name=%1
goto next
:C
set place=
:GetPlaces
shift /1
set param=%1
if not defined param goto donePlaces
if %param:~0,2% equ -- (
shift /1
goto processPlace
)
if %param:~0,1% equ - goto donePlaces
:processPlace
echo.%place%
if x%1 neq x (
set place=%place% %1
goto GetPlaces
)
:donePlaces
rem remove leading space
if defined place set place=%place:~1%
goto loop
:done
echo num=%first_number% name=%name% place=%place%

there's no switch command in batch.You need to workaround this with if statements:
#echo off
setlocal enableDelayedExpansion
for /l %%a in (1,2,6) do (
set /a next=%%a+1
set param=%%a
call set _param=%%!param!
call set _next=%%!next!
rem echo -!next! -!_next! #!_param! #%%a
if "!_param!" equ "-a" (
set first_number=!_next!
)
if "!_param!" equ "-b" (
call set name=!_next!
)
if "!_param!" equ "-c" (
set place=!_next!
)
)
for %%a in (place first_number name) do (
if not defined %%a set wrong_parameter=1
)
if defined wrong_parameter (
echo wrong parameter
)
echo %place% %first_number% %name%

Related

Return value from a cmd function

I have a batch function and I need to return a value from it. Following is the script:
#echo off
call :Mode mode1
echo mode is %mode1%
:Mode
setlocal enabledelayedexpansion
set count=0
for /f "tokens=*" %%x in (map.txt) do (
set /a count+=1
set var[!count!]=%%x
)
for /f "tokens=2 delims=: " %%A in ("%var[2]%") Do (
set mode=OPEN
)
IF %mode%==OPEN (
echo coming into open
set %1=OPEN
echo %mode1%
) ELSE (
echo coming into shorted
set %1=SHORTED
echo %mode1%
)
EXIT /B 0
echo mode is %mode1% doesn't print anything. Any help? I've hardcoded set mode=OPEN for testing purposes.
Each exit, exit /b or goto :eof implicitly does an endlocal, so you need a trick for your variable %1 to survive an endlocal. endlocal & set ... & goto :eof does the trick because the whole line gets parsed in one go:
#echo off
call :Mode mode1
echo mode is %mode1%
goto :eof
:Mode
setlocal enabledelayedexpansion
set "mode=OPEN"
IF "%mode%" == "OPEN" (
echo coming into open
endlocal&set "%1=OPEN"&goto :eof
) ELSE (
echo coming into shorted
endlocal&set "%1=SHORTED"&goto :eof
)
For the same reason, echo %mode1% in your subroutine does not print the variable.
Note: I changed set and if syntax to recommended quoted syntax.

Split string in batch file

I am new to using batch files so could someone please help me split a string i am getting from a file.
I am using %USERPROFILE% to get my string.
The string is: "C:\Users\nicholas"
I would like to keep the C:\ part, but get rid of the \Users\nicholas part.
for /f "tokens=2 delims=\" %A in ('set userprofile') do echo %A\
See for /?
Also
echo %userprofile:~0,3%
If you carefully read the output of set /?, you'll find the answer:
May also specify substrings for an expansion.
%PATH:~10,5%
would expand the PATH environment variable, and then use only the 5
characters that begin at the 11th (offset 10) character of the expanded
result.
So, you can use something like this to get the first 3 characters of your string:
> echo %userprofile:~0,3%
C:\
I As you need the drive where where the users are located you can use directly
%systemdrive% variable - this is the drive where the windows is installed
II the easiest way to get a drive from path:
for %%a in ("%userprofile%") do echo %%~da\
%~da - expands a path to its drive only
III over-complicated but powerful way (split function that can be used for a different things):
#echo off
call :split "%userprofile%" "\" 1 drive
echo %drive%\
goto :eof
:split [%1 - string to be splitted;%2 - split by;%3 - possition to get; %4 - if defined will store the result in variable with same name]
::http://ss64.org/viewtopic.php?id=1687
setlocal EnableDelayedExpansion
set "string=%~2%~1"
set "splitter=%~2"
set /a position=%~3
set LF=^
rem ** Two empty lines are required
echo off
for %%L in ("!LF!") DO (
for /f "delims=" %%R in ("!splitter!") do (
set "var=!string:%%~R%%~R=%%~L!"
set "var=!var:%%~R=%%~L!"
if "!var!" EQU "!string!" (
echo "%~1" does not contain "!splitter!" >&2
exit /B 1
)
)
)
if "!var!" equ "" (
endlocal & if "%~4" NEQ "" ( set "%~4=")
)
if !position! LEQ 0 ( set "_skip=" ) else (set "_skip=skip=%position%")
for /f "eol= %_skip% delims=" %%P in (""!var!"") DO (
if "%%~P" neq "" (
set "part=%%~P"
goto :end_for
)
)
set "part="
:end_for
if not defined part (
endlocal
echo Index Out Of Bound >&2
exit /B 2
)
endlocal & if "%~4" NEQ "" (set %~4=%part%) else echo %part%
exit /b 0

How to check a string does not start with a number in Batch?

How can I check that the first character of a string is a letter and so that it is not a number, or rather a cipher? There are no spaces or special characters in this string.
#ECHO OFF
SETLOCAL
SET /a num=5678
CALL :initnum
SET "num=hello"
CALL :initnum
SET "num=4ello"
CALL :initnum
SET "num=hell0"
CALL :initnum
SET "num=he8lo"
CALL :initnum
SET "num="
CALL :initnum
ECHO(==============
SET /a nam=7654
SET "nem=hello"
SET "nim=4ello"
SET "nom=hell0"
SET "num=he8lo"
SET "nzm="
CALL :initnum2 nam
CALL :initnum2 nem
CALL :initnum2 nim
CALL :initnum2 nom
CALL :initnum2 num
CALL :initnum2 nzm
GOTO :EOF
:initnum
IF NOT DEFINED num ECHO NUM is empty, so it doesn't begin with a numeric&GOTO :EOF
FOR /l %%a IN (0,1,9) DO IF %num:~0,1%==%%a ECHO %num% Begins with numeric&GOTO :EOF
ECHO %num% Does NOT begin with a numeric
GOTO :eof
:initnum2
IF NOT DEFINED %1 ECHO %1 is empty, so it doesn't begin with a numeric&GOTO :EOF
CALL SET "$1=%%%1%%"
FOR /l %%a IN (0,1,9) DO IF %$1:~0,1%==%%a ECHO %1 (%$1%) Begins with numeric&GOTO :EOF
ECHO %1 (%$1%) Does NOT begin with a numeric
GOTO :eof
You should be able to get what you want from this demo.
#echo off
setlocal enableextensions disabledelayedexpansion
set "var=1hello"
for /f "tokens=* delims=0123456789" %%a in ("%var%") do (
if not "%%a"=="%var%" echo var starts with a number
)
If the var contents starts with a number, the token/delim management in the for command will remove it.
edited just to include the usual (included the previous code) and some less used options just in case someone is interested
#echo off
setlocal enableextensions disabledelayedexpansion
set "var=1hello"
echo(%var%
rem Option 1 - Use the for command to tokenize the string
rem A dot is added to handle empty vars
for /f "tokens=* delims=0123456789" %%a in ("%var%.") do (
if not "%%a"=="%var%." (
echo var starts with a number
) else (
echo var does not start with a number
)
)
rem Option 2 - Use set arithmetic and detect errors
rem This will fail if the string starts with + or -
set "%var%_=0"
set /a "test=%var%_" 2>nul
if not errorlevel 1 (
echo var does not start with a number
) else (
echo var starts with a number
)
rem Option 3 - Use substring operations and logic operators
set "test=%var%."
if "%test:~0,1%" GEQ "0" if "%test:~0,1%" LEQ "9" set "test="
if defined test (
echo var does not start with a number
) else (
echo var starts with a number
)
rem Option 4 - Use findstr
rem This is SLOW as findstr needs to be executed
echo(%var%|findstr /b /r /c:"[0-9]" >nul && (
echo var starts with a number
) || (
echo var does not start with a number
)
I think this is the simplest way:
#echo off
setlocal EnableDelayedExpansion
set digits=0123456789
set var=1something
if "!digits:%var:~0,1%=!" neq "%digits%" (
echo First char is digit
) else (
echo First char is not digit
)
The first character of var is tried to be removed from digits string. If such a char was a digit, digits string change; otherwise, digits string remains the same.
#echo off
setlocal
set "the_string=a23something"
for /l %%a in (%the_string% ; 1 ; %the_string%) do set "cl_string=%%~a"
if %the_string:~0,1% neq 0 if "%cl_string%" equ "0" (
echo does not start with number
) else (
echo starts with number
)
endlocal
Another approach is with FINDSTR which eventually will be slower as it is an external for cmd.exe command.
#echo off
set "the_string=something"
echo %the_string%|findstr /b /r "[0-9]" >nul 2>&1 && (
echo starts with number
) || (
echo does not start with number
)
This will work in your situation:
echo %variable%|findstr "^[a-zA-Z]" >nul && echo it starts with an alpha character
Using findstr with regexp :
#echo off
set "$string=2toto"
echo %$string:~0,1%|findstr /i "^-*0*x*[0-9][0-9]*$">nul && echo is NUM || echo Is not NUM
in place of echo is NUM or echo is not NUM you can use a goto to redirect your script the way you want it.
#echo off
set "$string=2toto"
echo %$string:~0,1%|findstr /i "^-*0*x*[0-9][0-9]*$">nul && goto:isnum || goto:isnotnum
:isnum
echo is NUM
exit/b
:isnotnum
echo is not NUM
You have to set the string as a variable; in this way you are able to extract substrings from a main string. Here is an example:
#echo off
set EXAMPLESTRING=12345abcde
set FIRSTCHARACTERSTRING=%EXAMPLESTRING:~0,1%
The result of this short script should be 1 in this case.
Then, you can set a series of conditions to verify whether the first character is a number or not:
if %FIRSTCHARACTERSTRING%==0 goto NUMBER
if %FIRSTCHARACTERSTRING%==1 goto NUMBER
if %FIRSTCHARACTERSTRING%==2 goto NUMBER
if %FIRSTCHARACTERSTRING%==3 goto NUMBER
if %FIRSTCHARACTERSTRING%==4 goto NUMBER
if %FIRSTCHARACTERSTRING%==5 goto NUMBER
if %FIRSTCHARACTERSTRING%==6 goto NUMBER
if %FIRSTCHARACTERSTRING%==7 goto NUMBER
if %FIRSTCHARACTERSTRING%==8 goto NUMBER
if %FIRSTCHARACTERSTRING%==9 goto NUMBER
goto LETTER
:NUMBER
echo The first character is a number!
goto EOF
:LETTER
echo The first character is a letter!
goto EOF
Maybe this is not the most efficient solution but it works fine and it is easier to understand.

batch file - validate parameters

i have a batch file which should take inputs "-input1", "-input2" and "-input3". Here i need to validate the paramters like if user give the input parameter as "-test" or "-blah" or anyother parameter, then i should throw the error as "unregonized parameter". How can i achieve this? i tried by iterating through the paramters as %1 %2 etc. but i could not achieve the required behaviour.
IF "%1"=="" (
GOTO :ERROR3
)
IF "%1"=="-input1" (
SET value1=%2
)
#IF "%3"=="-input1" (
SET value1=%4
)
#IF "%5"=="-input1" (
SET value1=%6
)
#IF "%7"=="-input1" (
SET value1=%8
)
IF "%1"=="-input2" (
SET value1=%2
)
#IF "%3"=="-input2" (
SET value2=%4
)
#IF "%5"=="-input2" (
SET value2=%6
)
#IF "%7"=="-input2" (
SET value2=%8
)
IF "%1"=="-input3" (
SET value3=%2
)
#IF "%3"=="-input3" (
SET value3=%4
)
#IF "%5"=="-input3" (
SET value3=%6
)
#IF "%7"=="-input3" (
SET value3=%8
)
// some codes here
:ERROR1
ECHO "ERROR1"
GOTO :END
:ERROR2
ECHO "ERROR1"
GOTO :END
:ERROR3
ECHO Usage SAMPLE.bat -input1 "value1" -input2 "value2" -input3 "value3"
:END
Any help..
Here is a simple example of shifting through the parameters
#echo off
setlocal
set "value1="
set "value2="
set "value3="
:Parse
set "Param=%~1"
if not defined Param goto Validate
if "%Param%"=="-input1" set "value1=%2" & goto Next
if "%Param%"=="-input2" set "value2=%2" & goto Next
if "%Param%"=="-input3" set "value3=%2" & goto Next
goto Error1
:Next
shift & shift
goto Parse
:Validate
if defined value1 if defined value2 if defined value3 goto Main
goto Error2
:Main
echo %value1% %value2% %value3%
goto End
:Error1
echo Invalid Parameter: %1 %2
goto End
:Error2
echo Usage %~nx0 -input1 "value1" -input2 "value2" -input3 "value3"
goto End
:End
endlocal
The Batch file below allows you to modify the number and name of the parameters changing just one line.
#echo off
setlocal EnableDelayedExpansion
rem Define the list of parameters
set params=-input1 -input2 -input3
rem Initialize the array of parameters and their values
set n=0
for %%a in (%params%) do (
set /A n+=1
set param[%%a]=!n!
set "value!n!="
)
:nextParam
set "param=%~1"
shift
if not defined param goto start
if defined param[%param%] (
set "value!param[%param%]!=%~1"
shift
goto nextParam
)
echo ERROR - Bad parameter: %param%
goto :EOF
:start
echo Values of given parameters:
echo/
for /L %%i in (1,1,%n%) do echo Value%%i = "!value%%i!"

Read each character of argument in a batch file

sample input in cmd:
test.bat /p 1,3,4
expected result:
1
3
4
my codes so far:
#echo off
set arg = %1
set var = %2
if (%1)==(/p) (
... need code that will read and print each character of var
)
There is a potential problem with your question. If test.bat is:
#echo %1%
Then
test 1,2,3
Prints:
1
Because, in this context, the comma is treated as an argument delimiter.
So you either need to enclose in quotes:
test "1,2,3"
Or use a different internal delimiter:
test 1:2:3
Unless you want the parts to be placed in %2, %3, etc., in which case you problem is solved by a trivial use of SHIFT.
For my solution I have elected to require quotes around the group parameter, "1,2,3" (though this is easily adapted for a different delimiter by changing delims=, to specify the character you want to use).
#echo off
setlocal ENABLEDELAYEDEXPANSION ENABLEEXTENSIONS
set args=%~2
if "%1"=="/p" (
:NextToken
for /F "usebackq tokens=1* delims=," %%f in ('!args!') do (
echo %%f
set args=%%g
)
if defined args goto NextToken
)
Call like:
readch.bat /p "1,2,3"
%~2 is used to remove the quotes.
The FOR statement parses args, puts the first token in %f and the remainder of the line in %g.
The `goto NextToken' line loops until there are no more tokens.
#echo off
if "%1"=="/p" (
:LOOP
echo %2
shift
set arg=%2
if defined arg goto :LOOP else exit >nul
)
set params=%%~2
if (%1)==(/p) (
set params=%params:,= %
)
if "%params%" NEQ "" (
call :printer %params%
)
goto :eof
:printer
:shifting
if "%%1" NEQ "" (
echo %%1
) else (
goto :eof
)
shift
goto :shifting
goto :eof

Resources