#!/usr/bin/env bash ## Run a command as a background process or kill all instances of the command if ## any are running. ## ## Usage: toggle [...] ## ## Dependencies: GNU coreutils, GNU sed, procps ## ## I use this script to play/stop my favorite white noise MP3 ## via a window manager key binding. set -euo pipefail shopt -s inherit_errexit die() { echo -e "$(basename "$0"): $1" >&2; exit 1; } [[ " $* " =~ ' --help ' ]] && sed -n 's/^## *//p' "$0" && exit (( $# >= 1 )) || die 'missing argument' cmd=$1; type "$cmd" &> /dev/null || die "command not found: $cmd" cmd_args=("${@:2}") pkill "${cmd::15}" || ($cmd "${cmd_args[@]}" &> /dev/null &)