0

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.

2

1 Answer 1

3

You can avoid the failed command causing an exit due to set -e if you move it into the if:

if free -m | grep 'buffers' &> /dev/null; 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

Also, it's not so great that free -m is executed twice. You could store it in a variable for repeated processing:

free=$(free -m)
if [[ $free =~ buffers ]]; then
    MEMORY=$(awk 'NR==3{printf "%.0f%%", $3*100/($3+$4)}' <<< "$free")
else
    MEMORY=$(awk 'NR==2{printf "%.0f%%", ($2-$7)*100/$2}' <<< "$free")
fi
echo $MEMORY
Sign up to request clarification or add additional context in comments.

1 Comment

+1. There are certain places where set -e cannot reach, and the command list of if is one of them (gnu.org/software/bash/manual/bashref.html#The-Set-Builtin)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.