0

How to get list of dates from an output of ps command to only show those processes beyond 30 days?

My goal is to kill these processes. I can easily do this by killall command.

E.g. killall -u user --older-than 1M

But we have an outdated version of that command to which --older-than is not available so I'm force to find another way.

One thing I'm thinking is to pass the list of processes to kill command but I couldn't figure it out how to only get the processes that are 30 days old and beyond.

If there's something like this:

ps --no-header -u username --sort=start_time -o user,pid,lstart | #get all processes beyond 30 days old | while read -r pid; do kill $pid; done

Edit: We're using procps version 3.2.8

2

With relatively recent versions of procps, you can use etimes as the elapsed time as a number of seconds:

ps -Ao etimes= -o pid= |
  awk -v n=30 '$1 >= n*86400 {print $2}' |
  xargs -r kill

(here assuming GNU xargs for its -r option)

Or:

ps -Ao etimes= -o pid= |
  awk -v n=30 '$1 >= n*86400 {print "kill", $2}' |
  sh

With older versions, you can revert to etime:

LC_ALL=C ps -Ao etime= -o pid= |
  awk -v n=30 '$1 ~ /^[[:digit:]]+-/ && 0+$1 >= n {print "kill", $2}' |
  sh

(that syntax is POSIX and should work on all POSIX compliant systems).

  • ps -Ao etimes= -o pid= doesn't work. Throws error ERROR: Unknown user-defined format specifier "etimes" – WashichawbachaW Aug 19 at 14:56
  • 1
    @WashichawbachaW, yes like I said, you need a relatively recent version of procps (where your version of ps seems to be coming from) and I gave an alternative for older versions – Stéphane Chazelas Aug 19 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.