markhuge MH\n s

Shell Pattern: Toggles

published:

signed with 0x683A22F9469CA4EB

tags:

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

About the Author

Mark Wilkerson

0x683A22F9469CA4EB

R&D engineer @ Twitch. Previously Blizzard, Hightail, Co-Founder @ SpeakUp

Mark is building open source tools to make web3 and decentralized self-ownership easy for regular people.

Live dev streams at Twitch.tv

More Posts