4

I want to store node1 node2 node3 in a variable so that it may be used as an input to other scripts.

However, I want to do so by using brace expansion given by bash like so: node{1..3}

I tried to have a variable nodes=node{1..3}, but when I use it as an argument ($nodes) to the script, it gets picked up literally and doesn't expand.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
Murtaza Raja
  • 139
  • 1

3 Answers3

9

To assign to an array, put the elements in parentheses:

nodes=(node{1..3})

When using the array, you need to tell bash explicitly that you want to expand it as an array.

mycommand "${nodes[@]}"

Due to a design quirk of arrays in ksh and bash, $node is the first element of the array, you need to explicitly ask for all the elements with the [@] indexation. As always, you need double quotes around the variable expansion; with [@], each element is placed into a separate word.

See the bash manual for more information.

node=node{1..3} doesn't work because brace expansion only happens in contexts that allow multiple words. An assignment to a scalar (string) variable only allows a single word. You also only get a single word when expanding the variable, since Bash does brace expansion before variable expansion.

ilkkachu
  • 133,243
  • 15
  • 236
  • 397
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
0

To the consideration of expert users:

$ mapfile -t arr < <(printf "%s\n" node{1..3})
$ printf "%s\n" "${arr[@]}"
node1
node2
node3

Source

schrodingerscatcuriosity
  • 12,087
  • 3
  • 29
  • 57
  • 2
    It seems slightly awkward to create a file that is then immediately read in again. It would be more straight-forward to assign the elements resulting from the brace-expansion directly to the array with `arr=(node{1..3})`. – Kusalananda Jan 25 '22 at 13:30
  • @they yes, that's the answer of Gilles 'SO- stop being evil', I was looking for an alternative. Duly noted. – schrodingerscatcuriosity Jan 25 '22 at 13:32
-2

Found the answer after looking at this question: What is the rationale behind $array not expanding the whole array in ksh and bash?

nodes=$(echo nodes{1..3})
Greenonline
  • 1,759
  • 7
  • 16
  • 21
Murtaza Raja
  • 139
  • 1
  • 4
    That sets `nodes` to the string `nodes1 nodes2 nodes3`, not to an array of three elements. This may end up working as desired if node names can't contain whitespace or any of `?*\[` and you use the variable as `$nodes`. – Gilles 'SO- stop being evil' Jan 25 '22 at 12:44