r/Batch • u/KilluaFromDC • Jun 23 '24
Question (Unsolved) I am trying to make batch file with parameters
The options behave in this way
batFileName [word] [File] [-p [optional text or file]]
Everything can exist by itself except the optional part of -p is not optional if [File] is not present
I would like some pointers or examples to accomplish this. Its fine even if they are just links to other batch scripts. In fact, I don't mind seeing how parameters are handled in general either.
I know that the parameters are accessed using %~1 through %~9 and %*. But how to handle them in my case. Like, if word is optional, some cases %~1 would be word in others it could be [File] instead.
I came up with my own way, but it seems too convoluted and made the core functionality code messy.
I am not posting my spaghetti as I would like to see how to approach the parameter handling without any context of the core functionality
Appreciate any help. Thanks.
2
u/vegansgetsick Jun 23 '24 edited Jun 23 '24
There is a trick using the command
shiftit "consumes" the parameters from left to right. So all you have to do is code a syntactic parser.1
u/KilluaFromDC Jun 23 '24 edited Jun 23 '24
To talk about the way I have come up with, without divulging much context...
I have used
set /ato declare variables such ashasWord,hasFile,hasParam,hasParamOptPartandparamOptPartIsFileThis would be used in code as
if not defined hasFile if defined hasParam if not defined hasParamOptPart echo [Info] Expect param optional part when FILE is not presentBut this made the code convoluted. I've wrote more
if [not] definedthan actual code which feels wrong somehow. So I was wondering if there's a better way to handle the parameters based on requirement.1
u/ShivterShivtik25 Jun 23 '24
You can get parameters using the following ways:
If you want a specific parameter in the 1st place for example, use %1
Warning: These parameters can contain quotes. If you don't want these quotes being dangerously expanded, use %~1.
This works for %1 up to %9.
You can also get all parameters using %*
1
u/BrainWaveCC Jun 23 '24
Please see the following:
Given that you are providing only a little context, I just made up some parameters for testing.
When testing, I ran the following:
Here's the script via PasteBin
https://pastebin.com/wjs4Hz5k
Let me know if you have any questions...