Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

shell Associate Array not printing out all elements 1

Status
Not open for further replies.

rigstars2

Instructor
Dec 18, 2011
64
US
#!/opt/local/bin/bash

THRESHOLD=0
SUBJECT_HOURLY="'Hourly'"
SUBJECT_DAILY="'Daily'"

DAILY=`df -h | grep -i "/Volumes/Daily" | awk '{print $5}' | sed "s/%//"`
HOURLY=`df -h | grep -i "/Volumes/Hourly" | awk '{print $5}' | sed "s/%//"`

declare -A MyArray
MyArray=( [$HOURLY]=$SUBJECT_HOURLY [$DAILY]=$SUBJECT_DAILY )


for KEY in "${!MyArray[@]}"; do
echo "$KEY" "${MyArray[$KEY]}"
done

------------------
Expected result:
2 'Hourly'
2 'Daily'

Wrong result I always get is:
2 'Daily'

Why is my code not printing out the 1st key/value? It seems to skip the 1st key/value every time. Even if I swap the key pairs positions,
it just prints the 2nd key/value.

 
Hi

rigstars2 said:
Expected result:
2 'Hourly'
2 'Daily'
How could it do that ? I am not aware of any programming language where an array/associative array/hash/map can have more than one entries with identical index/key. If both HOURLY and DAILY have the same value 2, then the later added one will overwrite the previously added.


Feherke.
feherke.github.io
 
feherke,

You are right on! The keys cannot be the same but the values can be. Just re-arranged MyArray and works great now! Appreciate the assist!

#!/bin/bash

SUBJECT_HOURLY="Disk 'Hourly'"
SUBJECT_DAILY="Disk 'Daily'"

DAILY_VALUE="2"
HOURLY_VALUE="2"

declare -A MyArray
MyArray=( [$SUBJECT_HOURLY]=$HOURLY_VALUE [$SUBJECT_DAILY]=$DAILY_VALUE )

for KEY in "${!MyArray[@]}"; do
echo "$KEY" "${MyArray[$KEY]}"
done

---------
Disk 'Hourly' 2
Disk 'Daily' 2
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top