Wednesday 30 April 2008

Batch Programming Tip #04: Working with arguments - Part 3

6. Using SHIFT

I mentioned previously that you cannot assign more than 9 arguments to a batch call.
Well, that isn't altogether true because the shift command will allow you to read any number of arguments by replacing %1 with %2, %2 with %3, ... on each call.

Let's get straight to a real example (let's call it shiftargs.bat):

@echo off


We will use the arg_count variable to count the number of variables and show this at the end of the program.

:init_vars
set arg_count=0
goto load_args


Now let's load the arguments recursively and do something with each.


:load_args
if "%1" == "" goto end_script
set current_arg=%~1
goto action


In the action part we keep track of the argument count and more importantly shift to the next. Once we have called shift we have in effect "lost" %1 which has been replaced with %2 which itself is replaced with %3, etc.

:action
set /A arg_count+=1
shift
echo Argument %arg_count%: %current_arg%
goto load_args


At the end of the script, we display the argument count or a specific message if non were passed.


:end_script
if %arg_count%==0 goto no_args
echo Number of arguments: %arg_count%
goto eof

:no_args
echo No arguments provided.
goto eof


We finish it all off with the usual.

:eof
echo Press any key to quit...
pause > NUL
goto blackhole

:blackhole



If you just run the batch without passing any arguments it will display:

No arguments provided.
Press any key to quit...


We can also create an additional batch to call our shiftargs.bat with command line arguments as follows:

@echo off

call shiftargs the hungry fox and lovely plump goose are both peckish and so am I


This will of course display something more interesting:

Argument 1: the
Argument 2: hungry
Argument 3: fox
Argument 4: and
Argument 5: lovely
Argument 6: plump
Argument 7: goose
Argument 8: are
Argument 9: both
Argument 10: peckish
Argument 11: and
Argument 12: so
Argument 13: am
Argument 14: I
Number of arguments: 14
Press any key to quit...


And there we have it, we have passed more than 9 arguments to our batch command!

Bye for now.

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory