3

I have written a bash script that I manually start when logging in onto the laptop, but I want it to stop running when I lock my laptop.

This doesn't seem a very standard scenario, but I don't want to always manually stop the bash script when I go for a bathroom break and lock my MacBook.

3

You could modify your script with a while loop, that tests if you have locked the screen or not.

Here is a python approach, that checks for an active session.

And here is a way on implementing this python part into a bash script.

The answer in the first link also provides a Shell implementation, that could work for you too, but I was unsure, so I gave you another link.

Update :
Because I wanted to solve the problem, here is what I came up with:

#!/bin/bash
loop=$(python -c 'import sys,Quartz; d=Quartz.CGSessionCopyCurrentDictionary(); print d' | grep "CGSSessionScreenIsLocked = 1")
while [ "$loop" = "" ]; do
    echo "not locked"
    loop=$(python -c 'import sys,Quartz; d=Quartz.CGSessionCopyCurrentDictionary(); print d' | grep "CGSSessionScreenIsLocked = 1")
done
echo "locked"

However, If your script is one giant task, then the while loop won't help you.

In general, I think, it is rather difficult to trigger something on system lock. You probably need some helper application that watches the process and stops it when you lock the screen.

Taking this a step further : You could write a small programm/script that can check if your script is running and pause it, and when you are back at your desk and unlock the screen, it continues.

  • Works perfectly! – ujjain Jul 2 '14 at 14:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .