I have this code in a tool I am currently building:
while [ $# -gt 0 ]; do
case "$1" in
--var1=*)
var1="${1#*=}"
;;
--var2=*)
var1="${1#*=}"
;;
--var3=*)
var1="${1#*=}"
;;
*)
printf "***************************\n
* Error: Invalid argument.*\n
***************************\n"
esac
shift
done
I have many options to add, but five of my options should be saved as arrays. So if I call the tool, let's say from the shell using something like this:
./tool --var1="2" --var1="3" --var1="4" --var1="5" --var2="6" --var3="7"
How can I save the value of var1
as an array? Is that possible? And, if so, what is the best way to deal with these arrays in terms of efficiency if I have too many of them?.
Best Answer
If on Linux (with the
util-linux
utilities includinggetopt
installed, or the one frombusybox
), you can do:That way, you can call your script as:
And getopt will do the hard work of parsing it, handling
--
and abbreviations for you.Alternatively, you could rely on the type of the variable instead of specifying it in your
$opt_spec
associative array definition:You can add short options like: