how to redirect printf to a variable
$ a=$(printf "%08x" 22)
$ echo $a
00000016
this is not working
here is my code for
#!/bin/bash
FREE=`free -m | awk '/^Mem:/ { printf( "%s\n", $4 ); }'`
USED=`free -m | awk '/^Mem:/ { printf( "%s\n", $3 ); }'`
TOTAL=`expr $FREE + $USED`
awk -v TOTAL=$TOTAL -v FREE=$FREE -v USED=$USED '
BEGIN {
printf "FREEPER: %3.2f%%\n", FREE / TOTAL * 100
printf "USEDPER: %3.2f%%\n", USED / TOTAL * 100
exit
}'
i would like to pass each printf output to a variable
I don't follow your explanation, but...
#!/bin/bash
free -m | awk '/^Mem:/ { f+=$4; u+=$3 } END {t=f+u; printf("FREEPER: %3.2f\n USEDPER: %3.2f\n", f/t*100, u/t*100)}'
this is really simplified but any chance to pass FREEPER and USEDPER to two variables
it's possible:
free -m > /tmp/foo$$; eval $(awk '/^Mem:/ { f+=$4; u+=$3 } END {t=f+u; printf("FREEPER=%3.2f\nUSEDPER=%3.2f\n", f/t*100, u/t*100)}' /tmp/foo$$); rm /tmp/foo$$; echo $USEDPER
What is it that you're after?
Most likely you don't have to pass the variables back to shell - everything could be down within awk itself...
to make this script run in continues time intervals
if for certain time span the USEDMEM is high then generate an ALERT
also avoiding using cron job
something to start with...
#!/bin/bash
typeset -i thrF=80
typeset -i thrU=90
typeset -i sleepPeriod=10
while :
do
free -m | awk -f tF=${thrF} -v "${thrU}"'/^Mem:/ { f+=$4; u+=$3 } END {t=f+u; freeper=f/t*100; usedper=u/t*100
; if (freep>thrF) printf("freeper > thresholdFree\n"); if (usedp>thrU) printf("usedper > thresholdUsed\n")}'
sleep "${sleepPeriod}"
done
It is definitely working. I copy and pasted the command and its result.
You should have explained in your posting you were expecting awk printf to be redirected in a variable. Without context, it's hard to guess.
Here is probably what you are looking for, although there are a lot of potential optimizations:
FREE=`free -m | awk '/^Mem:/ { printf( "%s\n", $4 ); }'`
USED=`free -m | awk '/^Mem:/ { printf( "%s\n", $3 ); }'`
TOTAL=`expr $FREE + $USED`
FREEPER=$(awk -v TOTAL=$TOTAL -v FREE=$FREE -v USED=$USED 'BEGIN {printf "%3.2f%%",FREE/TOTAL*100;exit}')
USEDPER=$(awk -v TOTAL=$TOTAL -v FREE=$FREE -v USED=$USED 'BEGIN {printf "%3.2f%%",USED/TOTAL*100;exit}')