英文:
syntax error: invalid arithmetic operator in bash addition
问题
我遇到错误:“line 9: 0.0000: 语法错误:无效的算术运算符(错误标记为“.65”)”:
请建议如何修复此问题
尝试了这个:
#!/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"
期望输出:
56.65
看到的输出:
./top_gNB1.sh: line 9: 0.0000: 语法错误:无效的算术运算符(错误标记为“.0000”)
./top_gNB1.sh: line 9: 56.65: 语法错误:无效的算术运算符(错误标记为“.65”)
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
得分: 1
Bash只能进行整数运算,所以当你给它一个小数点时会得到语法错误。
改成:
cpu_sum=$(echo $cpu_sum + $cpu | bc)
英文:
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)
答案2
得分: 0
尝试一下这个未经测试的方法,让awk来进行算术计算:
#!/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"
IFS=' ' read -r -a pids <<< $(echo $(pgrep nr-softmodem -d ' ') )
这一行可以进行优化,但这是另一个问题。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论