1

I have the following ksh script, where $an_unset_var is an unset variable which is being used for the first time:

read -A arr <<< "$an_unset_var"
echo ${#an_unset_var}
echo ${#arr[*]}

Executing which, I get the following output:

0
1

Why does reading an unset variable into an array using the read command enter an empty element in the array? Why would this empty element be considered a valid countable element of the array?

closed as off-topic by Kusalananda, GAD3R, roaima, Timothy Martin, Jeff Schaller Apr 24 '18 at 22:40

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question has been posted on multiple sites. Cross-posting is strongly discouraged; see the help center and community FAQ for more information." – Kusalananda, GAD3R, roaima, Timothy Martin, Jeff Schaller

0

You read an empty string into the array. The array is unset and then it's first element is set to the empty string.

The empty string is a perfectly valid piece of data. I'm not sure what you were expecting to happen.

The equivalent set of commands would be

unset arr
arr[0]=""

arr is now an array with one element. Its element is the empty string.

  • I think part of the question here is why ksh behaves differently from bash here... On bash: read -a arr <<< ""; echo ${#arr[@]} returns 0... (And no, I don't really know why...) – filbranden Apr 24 '18 at 17:28
  • @FilipeBrandenburger Huh. I would almost consider that a bug in bash. – Kusalananda Apr 24 '18 at 17:29
0

Just a comment: difference between bash and ksh

$ ksh -c 'read -A a <<<""; typeset -p a'
typeset -a a=('')

$ bash -c 'read -a a <<<""; declare -p a'
declare -a a='()'

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