Search code examples
bashterminalsleepautomator

Creating a Service with automator, caffeinate


First of all, sorry for my english, not a native speaker.
Since I'm a bit fed up opening Termninal and ^C I want to create a shortcut for activating caffeinate -d on my Mac OS X 10.11
I've been trying a simple Automator Service but with my noob skills it doesn't work.

This is the settings:
I chose Service as type of document

Library->Utilities->Run Shell Script
Service receives: no input
in: any application
Shell: /bin/bash
Pass input: to stdin

CAFFEINATECHECK=`ps | grep caffeinate | cut -d ' ' -f7,8`
if [ $CAFFEINATECHECK == 'caffeinate -d' ]; then
killall caffeinate
else
caffeinate -d
fi

Problem is that such a short scrip keeps running with no response and I have to stop it after a minute
I hope someone could give me any tips necessary


Solution

  • I got the solution in a duplicate on Ask Different

    In short, just replacing mine code with a more elegant command lines:

    if [[ $(pgrep caffeinate) == "" ]]; then
        caffeinate -d &
    else
        pkill caffeinate
    fi 
    

    The only change I made inside user3439894's solution was to remove the '&' (usually useful at the end of a command line to run it in background) because apparently Automator doesn't work well with it (shame I can't remember where I read/heard that..!) .

    After saving the Service I just had to

    1. Open System Preferences Keyboard->Shortcuts->Services
    2. Bind my shortcut with my saved workflow found under ▼General in the right pannel

    This way a cog gear wheel ⚙ appears on the menubar when caffeinate shortcut is activated and spins till I deactive it .