堆内存对比Shell脚本执行时行2、3报command not found错误排查
Shell脚本变量赋值报错的原因与解决方法
问题场景
编写了用于对比堆内存的Shell脚本,代码如下:
#!/bin/bash $a=$(jcmd `jps -l | grep com.adobe.coldfusion.bootstrap.Bootstrap | cut -f1 -d ' '` GC.heap_info | awk 'NR==2 {print $5}') $b=1000000K if [[ $a -ge $b ]] then echo "The heapmemory used is greater." else echo "The heapmemory used is small." fi
执行./testscriptforheap.sh时,输出结果正确,但始终在第2行和第3行出现错误提示:
./testscriptforheap.sh: line 2: =1603644K: command not found ./testscriptforheap.sh: line 3: =1000000K: command not found
错误原因
Shell变量赋值的核心规则是变量名前不能加美元符号$。你在赋值时写了$a=...和$b=...,Shell会把$a解析为当前变量a的值(此时a未定义,值为空),导致整个语句变成=1603644K,Shell会把这个当作命令去执行,自然找不到对应命令,从而抛出错误。
解决方法
去掉变量赋值语句中变量名前的$符号,正确的赋值语法为变量名=值。注意:赋值符号=前后不能有空格(你的代码这部分符合要求)。
修正后的脚本
#!/bin/bash a=$(jcmd `jps -l | grep com.adobe.coldfusion.bootstrap.Bootstrap | cut -f1 -d ' '` GC.heap_info | awk 'NR==2 {print $5}') b=1000000K if [[ $a -ge $b ]] then echo "The heapmemory used is greater." else echo "The heapmemory used is small." fi
内容的提问来源于stack exchange,提问作者dante alighieri
相关产品推荐
相关产品推荐

