Github Code Search is an indispensable part of my workflow that I don’t think gets mentioned enough. There are so many great projects out there that solve or may help you solve what you are currently working on. I was looking to write a shell script to invoke the caffeinate command on macOS to keep my system awake. The default, this tool runs an blocks forever in the terminal while it does its job. I wanted to manage it in the background. I thought through the beginnings of how I might do that myself. Something like

ps aux | grep caffeinate
# if running, kill pid
# if not running, start

I plugged ps aux | grep caffeinate into Code Search and found several different approaches for what I had in mind. A language model does pretty well too.

#!/bin/bash

# This script toggles the 'caffeinate' command on macOS.

# Check if caffeinate is running
pid=$(pgrep caffeinate)

if [ -z "$pid" ]; then
  # If caffeinate is not running, start it
  caffeinate &
  echo "caffeinate started"
else
  # If caffeinate is running, kill it
  kill $pid
  echo "caffeinate stopped"
fi

I suppose the language model wins today, for introducing me to pgrep.

I settled on the following because I like one-liners:

pgrep caffeinate > /dev/null && kill $(pgrep caffeinate) || caffeinate -dim &