A bash shell example to query cpu/ram usage on k8s through kubernetes native tool kubectl:

#!/bin/bash
lines=$(kubectl top nodes | grep k8s-slave -c)
cpu=$(kubectl top nodes | grep k8s-slave |  awk '{ SUM += $3} END { print SUM}')
ram=$(kubectl top nodes | grep k8s-slave |  awk '{ SUM += $5} END { print SUM}')
cpu_usage=$[cpu/lines]
ram_usage=$[ram/lines]

if [ $cpu_usage -le 15 ]; then
  echo "too much wasted cpu resource!"
fi
if [ $ram_usage -ge 50 ]; then
  echo "ram's too low!"
fi

Attention this only applies to bash shell

  1. cpu_usage=$[cpu/lines] makes str to num. Otherwise you’ll see cpu_usage=53/3.
  2. can’t have space when assign value to a var, e.g x = "wrong".
  3. if needs to use [] for condition, and [] needs space for content, e.g [$wrong -le -15]
  4. To use linux cmd’s result to assign a var, use $(), e.g right=$(ls).

(变量值作为数字) 需要注意shell的默认赋值是字符串赋值。 错误方式:

var=1 
var=$var+1 
echo $var 

打印出来的不是2而是1+1。 正确方式:

  1. let “var+=1”
  2. var=$[$var+1]
  3. var=expr $var +1注意加号两边的空格,否则还是按照字符串的方式赋值 echo $var 打印出来是2 注意:前两种方式在bash下有效,在sh下会出错。[注意:我的虚拟机中:/bin/sh->/bin/bash] let表示数学运算; $[]将中括号内的表达式作为数学运算先计算结果再输出; expr用于整数值运算,每一项用空格隔开;[暂时无效]