djl
djl

Reputation: 277

How to combine a string and array

I have an array of numbers 0 10 20 30 40 and I am trying to add a string to the front the array so that the output will look like this: 1D: 0 10 20 30 40

I've tried coding it this way:

string="1D: "
new=( $(( $string + ${array[@]} )) )
echo $new

Which gives me this error:

-bash: 1D: value too great for base (error token is "1D")

Can someone assist me in this problem?

Thanks!

Upvotes: 1

Views: 54

Answers (2)

sparrow
sparrow

Reputation: 228

If you need to prepend a string to an array you can do something like this

array=("0" "10" "20" "30" "40")
array=("1D:" "${array[@]}")
echo ${array[@]}

output will be

1D: 0 10 20 30 40

Upvotes: 0

anubhava
anubhava

Reputation: 785058

You can use:

array=(0 10 20 30 40)
string="1D:"
new=("$string" "${array[@]}")

Check new array:

declare -p new

declare -a new='([0]="1D:" [1]="0" [2]="10" [3]="20" [4]="30" [5]="40")'

Or else:

echo "${new[@]}"
1D: 0 10 20 30 40

Upvotes: 2

Related Questions