I need to check utilized RAM percentage from shell script. But I want to use "set -e" for it and this makes me a problem.
There are two version of free utility that has slightly different output. In order to use awk on output, I check which one of free command is, by grepping output for string "buffers" which appears in only one of them. If there is no such string, command has exit status = 1 which kills my script from executing due to set -e parameter.
I tried also adding "|| true" after grep command but this always sets exit code = 0, making my grep test useless.
set -e
free -m | grep 'buffers' &> /dev/null || true
if [ $? == 0 ]; then
MEMORY=$(free -m | awk 'NR==3{printf "%.0f%%", $3*100/($3+$4)}')
else
MEMORY=$(free -m | awk 'NR==2{printf "%.0f%%", ($2-$7)*100/$2}')
fi
echo $MEMORY
So how I can do this properly without turning off set -e parameter? Also any better idea then presented to get percentage of utilized RAM into variable is welcome.
set -eis not universally considered a good idea -- ignore the parable and skip to the exercises below if in a hurry. Reviewing the incompatibilities betweenset -eimplementations across various shells may further make the point of howset -ecauses bugs, as opposed to only solving them.[ $? == 0 ]is gratuitously incompatible, as==is not a valid comparison operator in POSIXtest; use=instead, if you must compare$?at all (as opposed to just putting the content to be tested into the body of theif).