Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

batch file - Adding switches to command line arguments

I want to create my own command in following manner which I wish to run from both batch and cmd.exe:

fake-command -name <some value> -age <some Value>

Currently I know to create a command as following:

fake-command  <some value> <another Value>

After that I can collect the input as %1 and %2. But that is no efficient way to do this because what happens if the order in which I am expecting the input gets changed and someone enters age before name.

So I have two questions:

  1. How to create Linux like switches on Windows command line?
  2. Is my approach correct? Is there a better way to do this?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
@ECHO OFF
SETLOCAL
SET "switches=name age whatever"
SET "noargs=option anotheroption"
SET "swindicators=/ -"
SET "otherparameters="
:: clear switches
FOR %%a IN (%switches% %noargs%) DO SET "%%a="

:swloop
IF "%~1"=="" GOTO process

FOR %%a IN (%swindicators%) DO (
 FOR %%b IN (%noargs%) DO (
  IF /i "%%a%%b"=="%~1" SET "%%b=Y"&shift&GOTO swloop
 )
 FOR %%b IN (%switches%) DO (
  IF /i "%%a%%b"=="%~1" SET "%%b=%~2"&shift&shift&GOTO swloop
 )
)
SET "otherparameters=%otherparameters% %1"
SHIFT
GOTO swloop

:process

FOR %%a IN (%switches% %noargs% otherparameters) DO IF DEFINED %%a (CALL ECHO %%a=%%%%a%%) ELSE (ECHO %%a NOT defined)

GOTO :EOF

Here's a demonstration.

Given you have 3 switches, name age whatever which accept one argument and two true switches, option and anotheroption which take no arguments, then running the above procedure as

q27497516 -age 92 /option goosefeathers /name fred

(q27497516.bat is my batchname here) will yield

name=fred
age=92
whatever NOT defined
option=Y
anotheroption NOT defined
otherparameters= goosefeathers

Convention is to use / as a switch indicator - a leading - is legitimate for a filename. Implementation depends on the programmer's whim. The above structure will allow any character - within cmd's syntax rules, naturally [ie. $_# OK, %!^ No, ! maybe () awkward]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...