bashrhellsof

How to kill all processes which have '/var/' string in the description?


I am using lsof to find out all processes which have /var/ in the description.

[root@localhost ~]# lsof | grep /var/ | less
systemd      1                          root  105u     unix 0xffff9b25fae49680      0t0      21311 /var/run/cups/cups.sock type=STREAM
systemd      1                          root  134u     unix 0xffff9b25f509cd80      0t0      21334 /var/run/libvirt/virtlogd-sock type=STREAM
systemd      1                          root  135u     unix 0xffff9b25fae49f80      0t0      21315 /var/run/.heim_org.h5l.kcm-socket type=STREAM
systemd      1                          root  137u     unix 0xffff9b25fae48d80      0t0      21318 /var/run/libvirt/virtlockd-sock type=STREAM
polkitd    745                       polkitd  mem       REG                8,3 10406312    2107847 /var/lib/sss/mc/initgroups
polkitd    745                       polkitd  mem       REG                8,3  6406312    2107846 /var/lib/sss/mc/group

I am now trying to kill all these processes using the following command:

kill -9 $(lsof | grep /var/)

But getting error:

-bash: kill: root: arguments must be process or job IDs
-bash: kill: 8w: arguments must be process or job IDs
-bash: kill: REG: arguments must be process or job IDs
-bash: kill: 8,3: arguments must be process or job IDs

Solution

  • You want to

    lsof | awk -v pattern="/var/" '$9 ~ pattern {print $2}'
    

    On my system, that seems to output lots of duplicates:

    lsof | awk -v pattern="/var/" '$9 ~ pattern {print $2}' | sort -u
    

    and pass that list of pids to kill using xargs

    lsof | awk -v pattern="/var/" '$9 ~ pattern {print $2}' | sort -u | xargs echo kill
    

    Remove "echo" if you're satisfied it's working as you expect.