[Solved] Reading Array And Send An Email

I am trying to find an example for reading an array instead of reading a file and send out an email in ksh. Can you please help is that possible?

Algorithm

#!/bin/ksh
i=0
set -A ARR

if [ a -ne b ]
then
let i=$[$i+1]
ARR[$i]="A does n't match with B"
fi

if [ p -ne q ]
then
let i=$[$i+1]
ARR[$i]="P does n't match with Q"
fi

 -- send an single email reading the array
IFS=$'\n' echo "${ARRAY[@]}" | sendmail ...

Do i need to read the array in a loop? it's not working

#!/bin/ksh

i=0
set -A ARR

if [ a -ne b ]
then
let i=$[$i+1]
ARR[$i]="A does n't match with B"
fi

if [ p -ne q ]
then
let i=$[$i+1]
ARR[$i]="P does n't match with Q"
fi

while [ $i -eq ${#ARR[*]} ]
do
IFS=$'\n' echo "${ARR[@]}" | mailx -s "Hello" xxx@abc.com
i=$i-1
done

No, you don't need to put it in a loop. [@] should become all array elements.

In what way is it "not working"?

May bad it is working

#!/bin/ksh
i="0"
a="1"
b="2"
p="3"
q="4"
set -A ARR

if [ a -ne b ]
then
ARR[$i]="A does n't match with B"
fi

if [ p -ne q ]
then
i=$i+1
ARR[$i]="P does n't match with Q"
fi

#IFS=$'\n' echo "${ARR[@]}" | mailx -s "Hello" abc@xyz.com
echo "${ARR[@]}" | mailx -s "Hello" abc@xyz.com

But how do i print new line after each array element?

A does n't match with B P does n't match with Q

That's what the IFS part of the statement was supposed to do.

You could try this instead:

printf "%s\n" "${ARRAY[@]}" | mail ...

It's working thank you
I am always curious about printf command, may i please know in what scenarios i should use printf and echo??

printf and echo are not substitutes for each other, they work very different ways. echo just prints what you give it, printf can format it in various ways.

If you want to print several newlines, printf is a good bet. You don't get echo -e everywhere, but printf works nearly the same way wherever you go.

If you want to print a string without a newline, printf can do that everywhere too. printf "%s" "mystring"

If you want to format numbers, printf can also do that for you.

printf "%.3f\n" 10
10.000

In fact it can do quite a few things, more than I have time to mention here. See man printf for details.

okay thank you, if it is not too much to ask may i know how to check if array is empty or not. Is the below approach is correct?

IF [ ${#ARR[*]} -gt 0 ] 
then
  printf "%s" "Array is not empty"
else
  printf "%s" "Array is empty"
FI

That looks correct.

Is there a way where I can combine the floating point number scale along with the string formatting, something like below

printf "%.3f %s\n" Difference is 10

Difference is 10.000

Yes, the format string uses one 'thing' per item. So:

printf "%s %.3f\n", "Difference is" "10"