0

I'm getting load average in a bash shell script like so

load=`echo $(cat /proc/loadavg | awk '{print $1}')`

I know piping to bc

load=`echo $(cat /proc/loadavg | awk '{print $1}') \> 3 | bc -l`

is used in almost all examples of how to cast $load as an int but this box does not have bc installed and I am not allowed to add it.

I tried

int=`perl -E "say $load - 0"`

I tried

int=${load%.*}

I tried

int=`printf -v int %.0f "$load"`

What I want to be able to do is

if [ "$int" -gt  3.5 ]; then

How do I get that to evaluate as intended?

2
  • Awk prints floating point? Do you mean you want it as an integer? Commented May 4, 2017 at 16:19
  • 1
    If you just want to test if it is greater than 3.5 all you need is awk. if awk '$1<3.5{exit 1}' /proc/loadavg;then do stuff ;fi Commented May 4, 2017 at 16:24

2 Answers 2

3

You can use awk to produce a success/failure depending on the condition:

# exit 0 (success) when load average greater than 3.5, so take the branch
if awk '{ exit !($1 > 3.5) }' /proc/loadavg; then
    # load average was greater than 3.5
fi

Unfortunately, since "success" is 0 in the shell, you have to invert the logic of the condition to make awk exit with the required status. Obviously, you can do this in a number of ways, such as changing > to <=.

Sign up to request clarification or add additional context in comments.

Comments

3

You don't need any external tools (like awk) to read this stuff. Load average from /proc/loadavg is always formatted with two decimal places, so you can do this:

read load _ < /proc/loadavg

if [ ${load/./} -gt 350 ]; then
  # do something
fi

6 Comments

@ULick - the read command uses word splitting to separate things into variables, and if there are fewer variables than words, puts the remainder of the line into the last variable. read load _ reads the first word, and puts the rest of the line into the throw-away variable $_.
@123 - Are we looking for a load average of 3.50, or 35.00? I went with the numbers in the question.
@ghoti Oh yeah, yeah for some reason i thought it was 35 after reading your answer, no idea why, just ignore my comment :)
@ghoti The part about the splitting I understood, was just wondering why you used a variable which used by the shell itself (expands to the last argument to the previous command... )
@ULick - Ah, I see. "Tradition" I guess. I've been doing this way since before bash was born, and afaik $_ is nothing in POSIX shell. Bash doesn't make this variable read-only, so I'm free to continue to use it as a throw-away. :)
|

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.