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 its PID
item is eventually passed to the kill
command (kill PID
) thus causing the error.
Either use -t
option for headless output, or ignore the first row with AWK:
awk 'NR > 1 { print $2 }'
where NR
is the record (line) number.
Note that kill
only sends SIGTERM
signal to the process, and the process may merely ignore it. If you want to terminate the process for sure, run kill
with -9
(-KILL
) option (refer to man 7 signal
for signal codes).