3

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?

1 Answer 1

4

$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[@]}"
Sign up to request clarification or add additional context in comments.

1 Comment

You can also use +=( ) to append to an array: packages+=(tools oracle)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.