Search code examples
bashmailx

Iterate over associative array and send a single mail over the contents


Below is the snippet from my script which I'm currently working.

AArr is an associative array that holds the queue names and its corresponding values(integer values) and an basic iteration over it(for) gives the below output:

for i in "${!AArr[@]}"
 do
   echo "NUMBER COUNT ON $i' is : ${AArr[$i]}"
done

NUMBER COUNT ON queue.hxi.1 is:  123
NUMBER COUNT ON queue.rui.4 is:  12
NUMBER COUNT ON queue.hxi.5 is:  35
NUMBER COUNT ON queue.fer.5 is:  1000
NUMBER COUNT ON queue.dcer.2 is:  45

I wanted to iterate the Assocative array but send only one e-mail in above format instead of sending mail for every iteration's key. I'm bit stumped on the logic to achieve that ? Any inputs would be really helpfull.Thanks.


Solution

  • Why can't just pipe the output of the for loop to the mail command. It could be very well possible that the command can read over from standard input via pipe. So all you need to do is

    for entry in "${!AArr[@]}"; do
       printf "NUMBER COUNT ON %s is : %d\n" "$entry" "${AArr[$entry]}"
    done | mail