I'm using a command-line app in an AppleScript, and I need the script to wait for the process to finish running before continuing. (And yes, I want the terminal to open and to see the app run.)
I wrote this code, based on an existing question:
activate application "Terminal"
tell application "System Events"
repeat until visible of process "Terminal" is true
end repeat
end tell
tell application "System Events" to keystroke "app_name option"
tell application "System Events" to keystroke return
delay 2
set thePID to do shell script "app_name option > /dev/null 2>&1 & echo $!"
repeat
do shell script "ps ax | grep " & thePID & " | grep -v grep | awk '{ print $1 }'"
if result is "" then exit repeat
delay 2
end repeat
-- more code...
Everything is working in my script, except for the part where I need it to wait for the command-line app to complete.
How can I make this work? What exactly does the part starting with set thePID
do?
CodePudding user response:
To get this to work properly, I removed:
set thePID to do shell script "app_name option > /dev/null 2>&1 & echo $!"
Then under repeat
I changed:
do shell script "ps ax | grep " & thePID & " | grep -v grep | awk '{ print $1 }'"
to:
do shell script "ps ax | grep app_name | grep -v grep | awk '{ print $1 }'"
And now my script works as I wanted it to!
The issue was that I was calling the app by keystroke in the script, and then later basically running a separate instance of it by running set thePID to do shell script "app_name option > /dev/null 2>&1 & echo $!"
.
I assume the answer may be something like tell application "System Events" to keystroke "app_name option > /dev/null 2>&1 & echo $!"
.
I was running a second instance of the program since I was unclear about how to properly utilize the example given in that old post I linked to.
So I searched around for how to get the PID
of running program in the terminal, and I saw that grep app_name
was a common piece to the puzzle. Same with ps -ax
...
So I followed my own assumption, removed the variable that called for the program to run again, and simply inserted that program's name into the grep
part of the string replacing the variable. And it worked.