Kill all shared memory segments in Linux

I recently whipped up a shell script to kill all (IPC) shared memory segments in Linux for a client on oDesk.com. He wound up going with another contractor’s offer, and so I figured I would post my script here for the benefit of all.

ipcs -m | cut -d' ' -f2 | grep '^[0-9]' | while read $x; do ipcrm -m $x; done

Here’s what the individual pieces do:

  1. ipcs -m – This command lists all current shared memory segments. (Using -s would list semaphores, etc.)
  2. cut -d’ ‘ -f2 – This command cuts 2nd column from the ipcs output, using spaces as its delineating mark.
  3. grep ‘^[0-9]’ – This command only allows results which begin with a number to pass through. (We don’t want the header output from ipcs to mess with our process.)
  4. while read $x… – This command iterates over the output from the previous commands—which, by this point, will be the identifying number belonging to each shared memory segment—and runs the ipcrm IPC removal command against that output.

If you’ve got an unruly list of shared memory segments on your Linux machine and you just want them all to go away, fret no longer!