Although (as you have seen), you can combine expressions using logical ||
in GNU bc (and in busybox bc), it's not supported by POSIX1.
Since you're already using awk to parse the top
and free
outputs, an alternative approach would be to do the arithmetic and relational testing in awk as well - then you can use simple integer comparison in the shell (not even requiring bash):
#!/bin/sh
# This script monitors CPU and memory usage
RED='\033[0;31m'
NC='\033[0m' # No Color
limit=${1:-70.0}
while :
do
# Get the current usage of CPU and memory
top -bn1 | awk -v limit="$limit" '
/^%Cpu/ {printf "CPU Usage: %.1f%%\n", $2; exit ($2+0 > limit ? 1 : 0)}
'
cpuHi=$?
free -m | awk -v limit="$limit" '
/^Mem/ {usage = 100*$3/$2; printf "Memory Usage: %.0f%%\n", usage; exit (usage > limit ? 1 : 0)}
'
memHi=$?
sleep 1
if [ "$cpuHi" -ne 0 ] || [ "$memHi" -ne 0 ]
then
printf "${RED}The system is highly utilized${NC}\n"
else
printf "The system is not highly utilized\n"
fi
done
in fact, POSIX bc doesn't even support relational operators outside of a conditional construct or loop, ex.:
$ echo '2 > 1 || 1 > 2' | bc
1
but with warnings enabled:
$ echo '2 > 1 || 1 > 2' | bc -w
(standard_in) 1: (Warning) || operator
(standard_in) 2: (Warning) comparison in expression
1
and similarly with busybox
$ echo '2 > 1 || 1 > 2' | busybox bc -w
bc: POSIX does not allow boolean operators; this is bad: ||
bc: POSIX does not allow comparison operators outside if or loops
1