user3896519 user3896519 - 4 months ago 12
Bash Question

BASH:- Parse string into separate command line arguments

I have the following bash code and want to convert the string into command line arguments to pass to a different program.

So I have GETVARS and want to split and do something like

./somecommand $GETVARS[0] $GETVARS[1]

and so on

GETVARS will be any random length of elements.

GETVARS = ""
for id in {100..500..10}
do
for letter in A B C D E F
do
GETVARS=$GETVARS"\":${id}:${letter}\" "
done
done
//GETVARS = "":100:A" "100:B" "100:C"" .. and so on

Answer

To start with

getvars="" # no spaces around commas, use smaller case variable names

and from the requirement, you're clearly looking for a simple array like

getvars=() # or do declare -a getvars

I'm not clear about the requirement, but below is what I guess you should do

for id in {100..500..10}
  do
for letter in A B C D E F
  do
    getvars+=( \":${id}:${letter}\" ) # adding elements to array
 done
done
#and later do the following
./somecommand "${getvars[@]}" # Each element will be separated to a word