Im searching all over the internet , i guess im searching not the right keywords i tried most of them :)
i want to create in tcl/bash a proc with hyphen flags to get arguments with flags from the user
ex.
proc_name -color red -somethingselse black
The usual way to handle this in Tcl is by slurping the values into an array or dictionary and then picking them out of that. It doesn't offer the greatest amount of error checking, but it's so easy to get working.
Doing error checking takes more effort. Here's a simple version
With
array set
, we can assign the parameters and their values into an array.will produce the following output
It's very easy to do, actually. This code allows abbreviated option names, flag options (
-quxwoo
in the example) and the ability to stop reading options either with a--
token or with a non-option argument appearing. In the example, unknown option names raise errors. After passing the option-parsing loop,args
contains the remaining command-line arguments (not including the--
token if it was used).This is how it works. First set default values for the options:
Then enter a loop that processes the arguments, if there are any (left).
During each iteration, look at the first element in the argument list:
String-match ("glob") matching is used to make it possible to have abbreviated option names.
If a value option is found, use
lassign
to copy the value to the corresponding member of theoptions
array and to remove the first two elements in the argument list.If a flag option is found, set the corresponding member of the
options
array to 1 and remove the first element in the argument list.If the special
--
token is found, remove it from the argument list and exit the option-processing loop.If an option name is found that hasn't already been dealt with, raise an error.
If the first argument doesn't match any of the above, we seem to have run out of option arguments: just exit the loop.
Documentation: array, break, error, lassign, lindex, llength, proc, puts, set, switch, while