KSH返回值不是整数

时间:2014-10-10 05:59:51

标签: shell ksh

我有一个在数据库上执行查询(计数)的脚本,但结果不是整数,我试图用let来改变它,但没有运气

SQL="SELECT COUNT(*), INTRUDER FROM intruders WHERE UUR BETWEEN '${START}' and '${EINDE}' GROUP BY INTRUDER;"

实际的mysql命令

RESULT=$(mysql -u ${MYSQLUSER} -p${MYSQLPWD} -h ${SERVER} ${DATABASE} -BsNe "${SQL}")

计算

的循环
for RECORD in ${RESULT}
  do
    let TOTAL=$(echo ${RECORD} | awk '{print $1}')
    if [[ ${TOTAL} -ge ${MAXTRY} ]]; then
    ## Do something ....
    echo ${RECORD} | awk '{print $2}'
  fi
done

错误: ./script.sh [42]:let:TOTAL = 3 4 4 4:算术语法错误

2 个答案:

答案 0 :(得分:0)

管道sql的输出并循环遍历结果。 我添加了grep -v INTRUDER,我不知道你的输出中是否有标题记录。

TOTAL=0
mysql -u ${MYSQLUSER} -p${MYSQLPWD} -h ${SERVER} ${DATABASE} -BsNe "${SQL}" | 
   grep -v INTRUDER | while read intrudercount intrudername; do
      echo "Counting [${intrudername}]: ${intrudercount}"
      if [ ${intrudercount} -gt ${MAXTRY} ]; then
         echo "${intrudername} was very bad."
      fi
      (( TOTAL = TOTAL + ${intrudercount} ))
      echo "Subtotal until now: ${TOTAL}"
   done

答案 1 :(得分:0)

您可以使用awk来提取整数

`RESULT=$(mysql -u ${MYSQLUSER} -p${MYSQLPWD} -h ${SERVER} ${DATABASE} -BsNe "${SQL}")`

可以写成

`RESULT=$(mysql -u ${MYSQLUSER} -p${MYSQLPWD} -h ${SERVER} ${DATABASE} -BsNe "${SQL}"| awk "print $1")`

看看这是否解决了您的问题 假设您正在抑制查询给出的结果标题

,我已经写了上面的语句