I want to kill all processes given by lsof in a while loop.
this works fine:
lsof -i tcp | grep -v iceweasel | awk '{ print $2 }' | while read -r line
do
echo "$line"
done;
this one does not:
lsof -i tcp | grep -v iceweasel | awk '{ print $2 }' | while read -r line
do
kill "$line"
done;
The error generated by this last while is:
./kill.all.sh: line 6: kill: PID: arguments must be process or job IDs
any idea? thanks.
The problem is that the output of
lsof -i tcp
contains the header, and itsPID
item is eventually passed to thekill
command (kill PID
) thus causing the error.Either use
-t
option for headless output, or ignore the first row with AWK:where
NR
is the record (line) number.Note that
kill
only sendsSIGTERM
signal to the process, and the process may merely ignore it. If you want to terminate the process for sure, runkill
with-9
(-KILL
) option (refer toman 7 signal
for signal codes).