Execute shell script in background

It seems this "Execute Shell Script" action won't complete.


The goal is to run a command in the background and save its process ID to a variable so I can later stop it. More specifically, I want to disable system sleep while the macro is running.

I have tested this in an interactive shell (zsh) and in a shell script and it works in both cases, so I don't know why it doesn't work in KM.

I think you might need to assign the pid to a KM variable within the shell script. See here.

The method seems a little convoluted to me so I tried to find another way. The following seems to work.

  • At the start of your macro, put caffeinate on is own in an Execute Shell Script macro (the -i flag can be left out since this is the default behaviour).
  • Set the second menu for that command to asynchronously.
  • At the end of the macro, add another Execute Shell Script macro with the content killall -9 caffeinate

Hi Kevin. Appreciate the reply, but your alternative would stop all caffeinate processes, and that's a problem for me, because the macro is triggered when Image Capture launches (because copying large files fails when the system goes to sleep), but sometimes I run caffeinate for other reasons, for example when I use the VS Code Remote SSH extension (because it takes forever to reconnect). If I happened to be running caffeinate for one of those situations, and closed Image Capture during that, it would stop both processes.

I suppose I can use another program, like Amphetamine, for those situations. In this case your solution is good and I will mark it as such. Thanks!

However, I'm still curious why my original script action doesn't complete, if anyone knows the answer to that.

(Also: the environment variables in shell scripts aren't saved back to Keyboard Maestro, so writing the pid to KMVAR_pid won't work unfortunately.)

1 Like


You could make the shell script actions conditional on whether caffeinate were already running – or use global variables to keep track of the caffeinated state of apps e.g. check if "caffeinated_ssh" is "true"... but I can see that getting fiddly!

I need to revise all this..!

Caffeinate Screen Sharing Macro (v9.2)
"... it uses pgrep to automatically get the PID..."