【问题标题】:BASH, if statement not operating as expectedBASH,if 语句未按预期运行
【发布时间】:2021-07-15 12:53:33
【问题描述】:

正如标题所说,我试图只回显超过 2600000 秒的进程,但它会回显 etime 小于 2600000 的进程。

 while read pro; do
 set -- $pro

if [ $2 > 2600000 ]
 then
 echo $2 is bigger than 2600000
 echo "
PID :$1, Process owner :$3, procces begin time: $2 (Seconds ago)  
"
 fi
PIDS_OVER_A_MONTH+=("PID:$2, Process owner:$2")



done < <(ps -eo pid,etimes,user )

这是我的输出,如您所见,它回显小于 2600000 的 etime(不要注意到 PIDS_OVER... 列表):

PID :25271, Process owner :yonatanh, procces begin time: 2082286 (Seconds ago)  

2082286 is bigger than 2600000

PID :25275, Process owner :yonatanh, procces begin time: 2082286 (Seconds ago)  

2082284 is bigger than 2600000

PID :25299, Process owner :yonatanh, procces begin time: 2082284 (Seconds ago)  

7224 is bigger than 2600000

PID :29549, Process owner :it, procces begin time: 7224 (Seconds ago)  

6843 is bigger than 2600000

PID :30225, Process owner :yonatanh, procces begin time: 6843 (Seconds ago)  

2079327 is bigger than 2600000

PID :31324, Process owner :yonatanh, procces begin time: 2079327 (Seconds ago) 

【问题讨论】:

  • 尝试$2 -gt 2600000进行数字比较
  • @markp-fuso 我收到错误第 19 行:[: ELAPSED: integer expression expected
  • 另外,请注意您当前目录中的空文件2600000?如果您确实想与&gt; 进行字符串比较,则必须将其转义以防止其被视为重定向运算符。 [ $2 &gt; 2600000 ] 等价于 [ $2 ] &gt; 2600000
  • 这是一个极其常见的错误。我坚信解决该错误的一个简单方法是从不使用[。当你把它写成if test $2 &gt; 2600000 时,错误似乎更明显,因为读者不会被错误地认为[] 是语法的一部分而感到困惑。

标签: linux bash process ps


【解决方案1】:

你说的是bash,对吧?您需要移植到其他解析器吗?

我会使用bash

while read -r pid etimes user; do
  if (( etimes > 2600000 )); then
     echo "$etimes is bigger than 2600000"
     printf "\nPID :%s, Process owner :%s, proccess begin time: %s (Seconds ago)  \n\n" "$pid" "$user" "$etimes"
     PIDS_OVER_A_MONTH+=("PID:$pid, Process owner:$user")
  fi
done < <(ps -eo pid,etimes,user ) 

数字上下文(( )) 非常清楚。

【讨论】:

    【解决方案2】:

    几个建议的更改:

    • 使用-gt 进行数值比较
    • 添加--no-headers 以抑制ps 标题行
    • ps值直接读入变量

    综合起来:

    while read -r pid elapsed owner
    do
        if [ "${elapsed}" -gt 2600000 ]
        then
            echo "${elapsed} is bigger than 2600000"
            printf "\nPID : ${pid}, Process owner : ${owner}, procces begin time : ${elapsed} (Seconds ago)\n\n"
        fi
        PIDS_OVER_A_MONTH+=("PID:${pid}, Process owner:${owner}")
    done < <(ps --no-headers -eo pid,etimes,user )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      相关资源
      最近更新 更多