boardrider
boardrider

Reputation: 6185

How to add elements to a bash array?

I'm trying to add elements to a bash array, and I cannot figure out why they are not added:

$ cat /tmp/tmp.bash
#!/bin/bash

declare -a base=(
"python"
"python-setuptools"
)

packages=( "${base[*]}" "tools" "oracle" )
echo "$packages"

$ /tmp/tmp.bash
python python-setuptools
$ 

In the output, we only see the base array elements, but not the two I added.

Any idea what am I doing wrong?

Upvotes: 3

Views: 75

Answers (1)

John Kugelman
John Kugelman

Reputation: 361585

$packages expands to just the first element. To print all array elements write:

echo "${packages[@]}"

Similarly, when you expand $base you should use @ not *. * causes "python" and "python-setuptools" to be concatenated into a single array entry: python python-setuptools".

packages=( "${base[@]}" "tools" "oracle" )

Also note that there's no need to quote simple string literals. You could omit them.

base=(
    python
    python-setuptools
)

packages=("${base[@]}" tools oracle)
echo "${packages[@]}"

Upvotes: 4

Related Questions