Hi,
I have small application and from its menu item “Help” I am trying to run a shell script via terminal. I am successfully able to run the shell script, but i have a few confusion’s regarding opening of Terminal.app
here is my apple script snippet
activate application “Terminal”
tell application “System Events”
tell process “Terminal”
keystroke “/Users/bufferoverflow/shellscript”
keystroke return
end tell
end tell
the above code just works fine if Terminal.app is not running but if Terminal.app is already running and is “minimized” the above app script will not work. How do i overcome this?? Please help
My Terminal app does not have a menu like Shell > New Window > Basic.
I see that the original code only opens two windows if Terminal was not already running. Try this instead:
set command to "/Users/bufferoverflow/shellscript"
tell application "System Events" to set terminalAlreadyRunning to exists application process "Terminal"
tell application "Terminal"
activate -- If Terminal was running, just makes it frontmost. Otherwise, starts Terminal and opens a new window.
-- If the user has enabled the "Open a saved .term file when Terminal starts" option, and that .term file runs a command that does not terminate (like a continual status monitoring program) and Terminal was not already running, then the following code will end up sending the command to the window opened by the .term file where it will be ignored (because the initial command never exits). Unfortunately there does not appear to be a way to distinguish a default initial window from such a user-specified initial window. You can however, hope that a user that enables this option would know how to recover (copy and paste the command), or would already have Terminal running.
if terminalAlreadyRunning or not (exists first window) then
do script command -- uses new window
else
do script command in first window
end if
end tell
Here are a couple of methods I have used to run the script in the open window if it is idle, otherwise run it in a new window:
property command : "./Users/bufferoverflow/shellscript"
tell application "Terminal"
try
do script command in front window
on error
do script command
end try
end tell
property command : "./Users/bufferoverflow/shellscript"
tell application "Terminal"
try
set t_busy to busy of tab 1 of window 1
on error
set t_busy to true
end try
if t_busy then
do script command
else
do script command in front window
end if
activate
end tell
Use ralph’s method, though, if the user has no need to see the command or its result in a Terminal window.