3

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.

0

3 Answers 3

7

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.

0

To the consideration of expert users:

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

Source

2
  • 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}).
    – they
    Jan 25 at 13:30
  • @they yes, that's the answer of Gilles 'SO- stop being evil', I was looking for an alternative. Duly noted. Jan 25 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})
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. Jan 25 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.