Link to home
Start Free TrialLog in
Avatar of bhaskar20001
bhaskar20001Flag for India

asked on

Batch scripting :Argument reading

PROBLEM 1 :
I want to run a batch script (xyz.bat ) that takes ,say, 3 tags and their corresponding values :
Example of the command  : xyz.bat  -a 12 -b 23 -c 14

How can i  check how many arguments i have passed to this script and iterate over each and every argument .

I would want the script to take parse the command line arguments and perform the task based on the tag
The exact operation to be done :

Parse ( command line arguments )
if ( -a ) :
        set variable1 to 12
if ( -b ) :
        set variable2  to 23
if ( -c ) :
        set variable3  to 14

end

PROBLEM 2 :

how to check if the 2nd argument is a string and not null similar to
if [ -n $2 ] check ,  in shell scripts.
Avatar of knightEknight
knightEknight
Flag of United States of America image

REM - This batch file will set an environment variable for each tag you pass in.
REM - An empty tag will not create a variable, so if you pass in   -a 12 -b -c 14   ... there would be no "b" variable set.



@echo off

:loop

 if "%1"=="" goto done
 set token=%1

 if "%token:~0,1%"=="-" (set tag=%token:~1% & set val=) else (set val=%1)
 set %tag: =%=%val%
 shift

 goto :loop

:done
ASKER CERTIFIED SOLUTION
Avatar of knightEknight
knightEknight
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bhaskar20001

ASKER

Thanks a lot for the solution.I would like to know the following check also in batch :

if(2nd argument is string and not null )
{
do something
}

Thanks
There isn't really such a thing as a "null" argument to a batch file.  If by this you mean there is no matching value for a tag argument, you can do this if you know ahead of time what the possible tag values will be.


REM example:  C:\> xyz.bat -a 11 -b -c 33 -d 44



@echo off

setlocal

:loop

 if "%1"=="" goto done
 set token=%1

 if "%token:~0,1%"=="-" (set tag=%token:~1%) else (set %tag: =%=%1)

 shift

 goto :loop

:done

if "%a%"=="" (echo parameter a is null) else (echo parameter a is %a%)

if "%b%"=="" (echo parameter b is null) else (echo parameter b is %b%)

if "%c%"=="" (echo parameter c is null) else (echo parameter c is %c%)

if "%d%"=="" (echo parameter d is null) else (echo parameter d is %d%)

:end

endlocal
Thanks a lot for your help.It solved the problem
Thanks a lot for your help.It solved the problem