Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First index/value of sparse array

I have a sparse array in bash where I don't know the value of the lowest numbered index, and I want to pull that value out with its index. How do I find it?

#/bin/bash

a=( [12]="blue" [31]="violet" [59]="paisley" )

index=?

I want the first one.

like image 772
Graham Avatar asked Aug 23 '26 22:08

Graham


2 Answers

Transfer the numerical indices to an array and use its first element:

a=( [59]="paisley" [12]="blue" [31]="violet" )
arr=("${!a[@]}"); echo "${a[${arr[0]}]}"

Output:

blue
like image 78
Cyrus Avatar answered Aug 26 '26 22:08

Cyrus


Easy. Break a for loop.

#/bin/bash

a=( [12]="blue" [31]="violet" [59]="paisley" )

for index in "${!a[@]}"; do break; done

value="${a[$index]}"

echo "$index - $value"
like image 45
ghoti Avatar answered Aug 26 '26 22:08

ghoti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!