0

I have an AppleScript I use to set up my AppleTV screen sharing, sometimes it gets stuck and I have to kill it to try again. So I'd like to write a script that kills any running scripts and then run the script again.

Problem is I can't work out a way to do it that doesn't kill the parent script itself.

I can see using

ps axc

that the file has the path

/Applications/Connect Screen Mirroring - Master Bedroom.app/Contents/MacOS/applet

So I tried using

set PID to do shell script "(ps ax | grep \"Connect Screen Mirroring - Master Bedroom\" | grep applet | awk '{print $1}')"

do shell script "kill " & PID

But that gives me the error

sh: line 0: kill: 88944 89410 89411: arguments must be process or job IDs

I think the problem is that the first script is giving me back a 2nd, and sometimes a 3rd, unexpected PID, so if I could just find a way to filter that out I might be good.

If I run just

set PID to do shell script "ps ax | grep \"Connect Screen Mirroring - Master Bedroom\" | grep applet"

I get back

"89474 ?? S 0:00.33 /Applications/Connect Screen Mirroring - Master Bedroom.app/Contents/MacOS/applet 89485 ?? S 0:00.00 sh -c ps ax | grep "Connect Screen Mirroring - Master Bedroom" | grep applet"

Best as I can tell, that second thing getting returned is the shell command itself.

Any suggestions on how to ignore that one? Or a better way to do this altogether?

1 Answer 1

2

Here is how I'd do it:

In Terminal:

kill $(ps ax | awk '/[C]onnect Screen Mirroring - Master Bedroom/{print $1}')

Using the do shell script command in AppleScript:

do shell script "kill $(ps ax | awk '/[C]onnect Screen Mirroring - Master Bedroom/{print $1}'); exit 0"

Using awk eliminates the need to pipe to grep twice while allowing it to return only the value of the first column of ps output, which is the PID, and by placing square braces around the first character [C] it isolates the output to the occurrence being looked for, not what's generated by the awk command itself.

Using command substitution, $(...), it returns only the PID to the kill command.

2
  • Awesome, that works great! I just needed to put it in an if statement for when it's not there to kill and I'm golden. set PID to (do shell script "echo $(ps ax | awk '/[C]onnect Screen Mirroring - Master Bedroom/{print $1}')") if (PID is not equal to "") then do shell script "kill $(ps ax | awk '/[C]onnect Screen Mirroring - Master Bedroom/{print $1}')" end if Sep 17, 2021 at 8:34
  • @DrunkTankGunner, You do not need to use an if statement, simply add ;exit 0 directly after the command substitution, $(...);exit 0, which I forgot to add, sorry. See updated answer. Sep 17, 2021 at 11:39

You must log in to answer this question.

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