10

I'm having problems in bash (ver 4.2.25) copying arrays with empty elements. When I make a copy of an array into another variable, it does not copy any empty elements along with it.

#!/bin/bash

array=( 'one' '' 'three' )
copy=( ${array[*]} )

IFS=$'\n'

echo "--- array (${#array[*]}) ---"
echo "${array[*]}"

echo
echo "--- copy (${#copy[*]}) ---"
echo "${copy[*]}"

When I do this, here is the output:

--- array (3) ---
one

three

--- copy (2) ---
one
three

The original array has all three elements including the empty element, but the copy does not. What am I doing wrong here?

2 Answers 2

18

You have a quoting problem and you should be using @, not *. Use:

copy=( "${array[@]}" )

From the bash(1) man page:

Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with pathname expansion. If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word.

Example output after that change:

--- array (3) ---
one

three

--- copy (3) ---
one

three
Sign up to request clarification or add additional context in comments.

3 Comments

I doubt it - do you have both the @ and the double quotes? I just added some example output.
Oh, the double quotes! Sorry, didn't see the double quotes. Yep, that worked. So help me out, why do the quotes make this work?
With the double quotes and the @, that word expands to "one" "" "three". Without them, it expands to one three.
2

Starting with Bash 4.3, you can do this

$ alpha=(bravo charlie 'delta  3' '' foxtrot)

$ declare -n golf=alpha

$ echo "${golf[2]}"
delta  3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.