-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpsgrep
executable file
·97 lines (88 loc) · 1.79 KB
/
psgrep
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env ruby
# Start Date: Saturday December 6, 2008
# Current Version: 0.9
# Author: Joseph Pecoraro
# Contact: [email protected]
# Decription: Quicker handling of process searching
# and killing. Never type in a PID again, just regexes!
# -----------
# Globals
# -----------
kill_mode = false
icase_mode = true
pattern = nil
targets = []
pids = []
# ---------
# Usage
# ---------
def usage
puts "usage: #{$0.split(/\//).last} [options] pattern"
puts " -k or --kill kills all processes"
puts " -k# or --kill# kills the [#] process"
exit 0
end
# -----------
# Options
# -----------
if ARGV.size > 1
ARGV.each do |arg|
if arg.match(/^-(k|-kill)(\d*)$/)
kill_mode = true
targets << $2.to_i unless $2.empty?
elsif arg.match(/^-(i|-ignore)$/)
icase_mode = true
end
end
ARGV.delete_if { |e| e.match(/^-/) }
end
# -------------------
# Remaining Args
# -------------------
if ARGV.size != 1
usage
end
if icase_mode
pattern = Regexp.new( ARGV[0], Regexp::IGNORECASE )
else
pattern = Regexp.new( ARGV[0] )
end
# ----------------------
# Actual `ps` Output
# ----------------------
lines = %x{ ps -Au#{ENV['USER']} }.split(/\n/)
header = lines.shift
# ----------
# psgrep
# ----------
puts
puts " #{header}"
count = 0
lines.each do |line|
unless line =~ /psgrep/
if line.match(pattern)
count += 1
puts "[#{count}]: #{line}"
if targets.empty? || targets.member?(count)
pids << line.strip.split[1]
end
end
end
end
# -------------
# Kill Mode
# -------------
if kill_mode
puts
puts "Killing Processes"
puts "-----------------"
pids.each_with_index do |pid, i|
print targets.empty? ? "[#{i}]:" : "[#{targets[i]}]:"
print " Killing #{pid}... "
STDOUT.flush
res = %x{ kill #{pid} }
puts "Dead" if $?.exitstatus.zero?
end
end
# Always
puts