linux运行java项目时,指定当前空闲内存的80%运行项目,shell脚本获取当前80%空闲内存值的方法
MEMORY=`free | sed -n '2p' | awk '{print $4}'` USE_MEMORY_RATE=0.8
## 判断USE_MEMORY_RATE 值是否在0~1之间 PRODUCT=`bc << EOF scale = 0 a1 = $USE_MEMORY_RATE b1 = 10 a1 * b1 EOF` index=`expr index "${PRODUCT}" .` if [[ $index -ne 0 ]];then PRODUCT=${PRODUCT:0:${index}-1} fi if [[ $PRODUCT -ge 10 ]];then echo "USE_MEMORY_RATE should be greater than 0 and lower than 1,you set is ${USE_MEMORY_RATE}" exit fi if [[ $PRODUCT -le 0 ]];then echo "USE_MEMORY_RATE should be greater than 0 and lower than 1,you set is ${USE_MEMORY_RATE}" exit fi
# 算出80%内存的值,并进行取整。因为-Xmx 后不能跟小数 USE=`bc << EOF scale = 0 a1 = $MEMORY / 1024 b1 = $USE_MEMORY_RATE a1 * b1 EOF` INDEX=`expr index "${USE}" .` USE_MEMORY=${USE:0:${INDEX}-1} echo "engine use memory $USE_MEMORY M"