Adding an element to a bash array with a variable

Hello,

I have a simple task and I am having some trouble with the syntax. I have a variable with an assigned value,

CMD_STRING='-L 22 -s 0 -r -O -A i -N 100 -n'

I would like to add that variable to an array. As far as I have been able to look up, the syntax should be something like,

CMD_STRING_LIST=("${CMD_STRING_LIST[@]}" "$CMD_STRING")

This does not work and the array is empty, even though I can print the contents of $CMD_STRING . The only examples I can find of this technique use hard coded values to add to the array like,

LIST=("${LIST[@]}" "stuff1" "stuff2" "stuff3")

I find this kind of example to be a bit annoying because I can't envision many real world examples where I would hard code data to add to an array. At least I think it is far more likely for such data to exist in variables.

Am I using the wrong technique here or do I have the syntax wrong?

LMHmedchem

This seems to be working fine for me:

$ CMD_STRING='-L 22 -s 0 -r -O -A i -N 100 -n'
$ CMD_STRING_LIST=(1 2 3)
$ CMD_STRING_LIST=("${CMD_STRING_LIST[@]}" "$CMD_STRING")
$ echo ${#CMD_STRING_LIST[@]}
4
$ echo ${CMD_STRING_LIST[3]}
-L 22 -s 0 -r -O -A i -N 100 -n

I wonder if your doing this all within a loop and loosing the changes due to Bash sub-shell: variables lost

1 Like

Yes it is in a loop. I am trying to accumulate a list of commands to run later.

The post you linked to is interesting. I am sure I have done this kind of thing before, meaning accumulated data in an array from inside a loop. A loop is the most likely place where you would want to push allot of data into a structure. I do remember having some issues with the syntax before since I don't do it very often, but I don't remember it not working. Perhaps it matters where the array is declared. Is this like c++ where a variable declared in {} will not be in scope outside of the {}?

I will try to look for some other scripts where I have this method working.

LMHmedchem

It also seems that a simple string, rather than an array, might be a simpler approach here. When you get to the point that you want to invoke a command, I would assume that you would want -L 22 -s 0 -r -O -A i -N 100 -n to be eleven separate arguments to that command; not a single argument.

You may want to assign the results of the entire loop to a variable/array.