Bash shell脚本中的语法错误是什么

Bash shell脚本中的语法错误是什么,bash,shell,cpu-usage,script,Bash,Shell,Cpu Usage,Script,计算计算机的CPU负载并确定状态(未加载或未加载) 你的机器过载了。你必须了解你电脑的CPU使用情况 使用一些Unix命令 提示:借助grep Unix命令,您可以提取CPU使用情况。如果CPU负载为 大于过载的70%,如果在30%到70%之间 中等负荷,如果低于30%,则轻负荷 read -a currentRead <<< `top -bn1 | grep "Cpu(s)"` userProcess=${currentRead[1]} systemPro

计算计算机的CPU负载并确定状态(未加载或未加载) 你的机器过载了。你必须了解你电脑的CPU使用情况 使用一些Unix命令

提示:借助grep Unix命令,您可以提取CPU使用情况。如果CPU负载为 大于过载的70%,如果在30%到70%之间 中等负荷,如果低于30%,则轻负荷

read -a currentRead <<< `top -bn1 | grep "Cpu(s)"`
userProcess=${currentRead[1]}
systemProcess=${currentRead[3]}
totalUsage=`echo $userProcess + $systemProcess | bc` 
echo "TotalCPU_Usage: $totalUsage%"
$totalUsage=$( printf "%.0f" $totalUsage )
b=70
c=30
if [ "$totalUsage" -gt 70.0 ]
then 
echo "Overloaded"
elif [ $totalUsage -lt $c ]
then 
echo "Lightly-Loaded"
else
echo "Moderately Loaded"
fi


由于这是家庭作业,我将把它作为提示:

  • 简言之,不带引号的变量引用会产生奇怪的意外情况
  • Bash只支持整数,不支持分数、小数或浮点
  • 运行生成的脚本以获得更多提示,以改进代码并避免bug
  • 有几件事

    这表明您有整数和字符串比较,而这正是您所面临的问题,因为您有一些浮点数

    您可以添加-x以在bash中显示调试,也可以使用

    bash -x myscript.sh
    
    但这里是你工作的例子。我和你一样使用bc,但作为比较

    #!/bin/bash -x
    
    read -a currentRead <<< `top -bn1 | grep "Cpu(s)"`
    userProcess=${currentRead[1]}
    systemProcess=${currentRead[3]}
    totalUsage=`echo $userProcess + $systemProcess | bc` 
    echo "TotalCPU_Usage: $totalUsage%"
    #totalUsage=$( printf "%.0f" $totalUsage )
    high=70.0
    low=30.0
    
    
    echo "total usage $totalUsage"
    if [ $(echo "$totalUsage >= $high" | bc) -eq 1 ]; then 
        echo "Overloaded "
    elif [ $(echo "$totalUsage >= $low" | bc ) -eq 1 ]; then 
        echo "Lightly-Loaded"
    else
        echo "Moderately Loaded"
    fi
    

    您的作业
    $totalUsage=$(printf“%.0f”$totalUsage)
    是伪造的-删除前导的
    $
    [
    命令只支持整数运算。您需要使用
    [[/COD>支持浮点,如果可能的话,把一个SUBANG粘贴到@ VishalJangid:尝试用分数值进行数值比较。BASH只能做整数运算。考虑切换到ZSH,或者使用一个外部工具,如<代码> BC < /代码>用于您的算术。
    
    #!/bin/bash -x
    
    read -a currentRead <<< `top -bn1 | grep "Cpu(s)"`
    userProcess=${currentRead[1]}
    systemProcess=${currentRead[3]}
    totalUsage=`echo $userProcess + $systemProcess | bc` 
    echo "TotalCPU_Usage: $totalUsage%"
    #totalUsage=$( printf "%.0f" $totalUsage )
    high=70.0
    low=30.0
    
    
    echo "total usage $totalUsage"
    if [ $(echo "$totalUsage >= $high" | bc) -eq 1 ]; then 
        echo "Overloaded "
    elif [ $(echo "$totalUsage >= $low" | bc ) -eq 1 ]; then 
        echo "Lightly-Loaded"
    else
        echo "Moderately Loaded"
    fi
    
    [ $(echo "1.1 >= 1.1" | bc) == 1 ] && echo 'true' || echo 'false'