Discussion:
[Help-bash] What is the most efficient way to extract the first element of "${!x[@]}"?
Peng Yu
2018-02-22 04:57:09 UTC
Permalink
Hi,

I have to assign "${!x[@]}" to an array and then extract the first
element. If I understand it correctly, this will involve an extra copy
which may be slow for large arrays. Is there a syntax that allows the
direct extraction of the first element of "${!x[@]}"? Thanks.

$ x=()
$ x[10]=a
$ x[2]=b
$ i=("${!x[@]}")
$ echo "${i[0]}"
2
--
Regards,
Peng
Pierre Gaston
2018-02-22 07:09:53 UTC
Permalink
Post by Peng Yu
Hi,
element. If I understand it correctly, this will involve an extra copy
which may be slow for large arrays. Is there a syntax that allows the
$ x=()
$ x[10]=a
$ x[2]=b
$ echo "${i[0]}"
2
--
Regards,
Peng
I don't think there is something much better than this, you can probably
avoid some extra assignments eg:

x=([2]=b [10]=a)
for first in "${!x[@]}";do break;done;echo "$first"

But it will still be pretty slow on large array, maybe you could keep track
of it manually?

Loading...