yonatan hornstein
yonatan hornstein

Reputation: 233

BASH, if statement not operating as expected

As the title says, Im trying to echo only the process that older than 2600000 seconds, but it echos processes with etimes less than 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 )

This is my output, as you can see, it echos etimes that are less than 2600000 (don't notice PIDS_OVER... list):

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) 

Upvotes: 0

Views: 59

Answers (2)

Paul Hodges
Paul Hodges

Reputation: 15246

You did say bash, right? Do you need portability to other parsers?

I'd use 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 ) 

Numeric context (( )) makes it pretty clear.

Upvotes: 1

markp-fuso
markp-fuso

Reputation: 34024

A couple recommended changes:

  • use -gt for numeric comparisons
  • add --no-headers to suppress the ps header line
  • read ps values directly into variables

Pulling this all together:

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 )

Upvotes: 1

Related Questions