0

I am getting the error: "line 9: 0.0000: syntax error: invalid arithmetic operator (error token is ".65")":

Please suggest how to fix this

Tried this:

  #!/bin/bash

  IFS=' ' read -r -a pids <<< $(echo $(pgrep nr-softmodem -d ' ') )
  cpu_sum=0.0000;
  mem=0;
  for i in "${pids[@]}";
      do
     cpu=$(top -b -n1 -p "$i" -H | tail -n +8 | awk '{ if ($9 !=0) {sum += $9; count++} } END    {if (count !=0) {avg =sum/count; print avg}}')
 
         cpu_sum=$(echo $((cpu_sum +=cpu ))) 
 done
 echo "$cpu_sum"

Expected output:

56.65

Output seen:

./top_gNB1.sh: line 9: 0.0000: syntax error: invalid arithmetic operator (error token is ".0000")
./top_gNB1.sh: line 9: 56.65: syntax error: invalid arithmetic operator (error token is ".65")
0
1
  • There is no need to do $(echo $(( ... ))). It's equivalent to just doing $(( ... )). Also, add a space after the parentheses. Commented Jul 6, 2023 at 12:32

2 Answers 2

1

Bash can only do integer arithmetic, so you get a syntax error when you give it a decimal point.

Instead of:

         cpu_sum=$(echo $((cpu_sum +=cpu ))) 

Try:

         cpu_sum=$(echo $cpu_sum + $cpu | bc)
Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't work. It gives error: (standard_in) 2: syntax error
On which line does it give an error?
That sounds like $cpu is either empty or contains something other than a number. Maybe try something like xxd <<< "$cpu" to confirm it doesn't have any tricky characters in it before passing it into bc.
In your Awk script, you have END {if (count !=0) {avg =sum/count; print avg}} - so if count is 0, it will not print anything and cpu will be set to an empty string.
0

Try this, untested, letting awk do the artihmetic:

#!/usr/bin/env bash

IFS=' ' read -r -a pids <<< $(echo $(pgrep nr-softmodem -d ' ') )
cpu_sum=0
mem=0
for i in "${pids[@]}"; do
    cpu_sum=$(
        top -b -n1 -p "$i" -H |
        tail -n +8 |
        awk -v cpu_sum="$cpu_sum" '
            $9 { sum += $9; count++ }
            END {
                if ( count ) {
                    avg = sum / count
                }
                print avg + cpu_sum
            }
        '
    )
done
echo "$cpu_sum"

The line IFS=' ' read -r -a pids <<< $(echo $(pgrep nr-softmodem -d ' ') ) could be improved but that's a different question.

Comments

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.