Reputation: 2533
I'm trying to write a one-liner that would find all processes for a username older than 1 hour and kill them. I have the following:
for each in $(find /proc -maxdepth 1 -user hobbyisl -type d -mmin +60 -exec basename {} \;); do kill -9 $file; done
The following part is identifying the processes properly:
find /proc -maxdepth 1 -user hobbyisl -type d -mmin +60 -exec basename {} \;
When running the whole thing I get the following error:
kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
Can someone please help?
Upvotes: 0
Views: 2703
Reputation: 672
The killall
command supports this natively if you have that in whatever distro you are running:
killall -u foo -o 2m bar
-u foo
- specify a the user foo
-o 2m
- filter by processes older than 2 minutesbar
additional filter (only processes containing 'foo' in the command)Upvotes: 0
Reputation: 1780
Here is a one-liner using ps,awk,xargs. Replace user root
with the right one and remove echo
from the xargs in order to actually kill the process.
ps -u root -o pid,etime | awk '{split($2,t,":"); split(t[1],t,"-"); if (int(t[2])>1) print $1;}' | xargs -I _ echo kill _
To explain a bit:
note: this will work processes older than a day (because of the split thing in awk).
update: a little long awk but:
ps -u root -o pid,etime | awk '{split($2,t,":"); n=0; for(i in t) n++; if(n > 2) { split(t[1],a,"-"); j=0; for(i in a) j++; x=a[1]; if(j>1) {x=a[2]} if(int(x)>0) print $1 }}' | xargs -I _ echo kill _
Upvotes: 0
Reputation: 1446
In your loop the $each
(each
is not part of the syntax - it's a variable name) variable holds the process id and not $file
Try that:
for each in $(find /proc -maxdepth 1 -user hobbyisl -type d -mmin +60 -exec basename {} \;); do kill -9 $each; done
However, I recommend using variables like process_id
and not each
as it could lead to errors like that :)
Upvotes: 4
Reputation: 3721
Your for
statement uses the variable each
. Your kill
statement uses the variable file
. Thus, error.
Upvotes: 2