0

I'm writing a bash script, where I take in a large number of arguments. It looks something like this:

bash script.sh 713884440 1041 691539599 Digiweb 371449356 Dublin ...

Since there are a large number of arguments, and since the number of arguments differ depending on the situation, I wanted to build a string that takes all the arguments and puts it in this form:

element.713884440="1041" -d element.691539599="Digiweb" -d element.371449356="Dublin"...

I initially tried writing a for loop to do this. For the first iteration of the loop, I thought ${$i} would first evaluate to $1, then to 713884440

for i in $(seq 1 2 $#)
do
    ENT=$i
    VAL=$i+1
    ENTRYSTRING="$ENTRYSTRING -d element.${$i}=\"${${i+1}}\"";
done;

This didn't work. And I've tried having the "inner" variable resolve through echo and eval, but those didn't work either. How would I accomplish this?

JKing
  • 73
  • 6
  • It looks like you're preparing a list of arguments to be passed to some other command. If that's the case, you're going to run into trouble because embedding quotes in variables doesn't work at all like you'd expect. You should use an array instead. See ["bash quotes in variable treated different when expanded to command"](https://stackoverflow.com/questions/20037509/bash-quotes-in-variable-treated-different-when-expanded-to-command) and [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](http://mywiki.wooledge.org/BashFAQ/050) – Gordon Davisson Feb 06 '18 at 18:43
  • Thanks! This is what I ended up doing. – JKing Feb 06 '18 at 19:47

1 Answers1

1
S=""
while [ $# -ge 2 ]
do
  S="$S -d element.$1=\"$2\""
  shift 2
done
echo $S
Gerard H. Pille
  • 2,528
  • 1
  • 13
  • 17
  • While this would work for the first part of the string, I want it so that S would evaluate to `S="$S -d entry.$3=\"$4\""` on the second iteration of the loop – JKing Feb 06 '18 at 16:35
  • And what would you like for the third iteration? Perhaps you could show the end result? – Gerard H. Pille Feb 06 '18 at 17:26
  • @JKing The `shift 2` accomplishes that. It removes the first two arguments from the list, and shifts the rest down by two, so that on the second iteration `$1` refers to the third argument and `$2` to the fourth. Similarly, on the third iteration `$1` refers to the fifth argument and `$2` to the sixth, etc. – Gordon Davisson Feb 06 '18 at 18:37
  • Yes, but it's "element" for each iteration, he wants "entry" for the second. And the next? – Gerard H. Pille Feb 06 '18 at 18:41