markhuge

Shell Pattern: Toggles

Published by Mark on

Sometimes it’s handy to be able toggle programs or services on and off. Here’s one way to do that:

#!/bin/sh
prog="myprogram"

# See if program has an active process ID
if pidof -x "${prog}"; then
  # if so, kill it and exit cleanly
  killall "${prog}"
  exit 0
fi
# Otherwise start the program
"${prog}" &

Example

No matter what I do, I always have screen tearing when playing videos while picom/compton is running. I gave up on fixing this with config and just bound this picom toggle to a Fn Key and called it a day:

#!/bin/sh

if pidof -x "picom"; then
  killall picom
  exit 0
fi

picom &

Universal Toggle

You could take this further and write a universal toggle script that you pass a process name:

#!/bin/sh
prog="$1"

if pidof -x "${prog}"; then
  killall "${prog}"
  exit 0
fi
"${prog}" &

And then:

me@host $> toggle picom