I have a zsh script where I prompt for user input every 15 minutes. How can I make the tab of Terminal that the script is running in open up / focus? open -a Terminal
just opens the whole window.
I'm aware of this trick to get current application and re-open it, is there a way to extend it to tabs/sessions?
term=$(/usr/bin/osascript -e "copy path to frontmost application as text to stdout")
/usr/bin/osascript -e 'tell application $term to activate'
Also aware of this trick to go back to an old tab, although (1) I couldn't get it to work and (2) I need the data in stdout so zsh can use it.
osascript \
-e 'tell application "Terminal" to set oldTab to the selected tab of the front window' \
-e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down' \
-e 'delay 1' \
-e 'tell application "Terminal" to set selected of oldTab to true'
Best Answer
Based on your reply of "Yes, precisely. Well put." to my comment under the OP...
The following example AppleScript code used in conjunction with
osascript
in azsh
shell script should do as wanted. Obviously the value of thesleep
command is just for testing purposes, use whatever it is you are now using as the timer within your currentzsh
shell script.Notes:
In Terminal, it does not matter how may tabs/windows there are as there is only one
tab
perwindow
, even if the window appears to have multiple tabs. In other words, asking Terminal tocount windows
andcount tabs of windows
will return the same number. Thus there it no need to loop thrutabs
to achieve the goal herein, justwindows
, and actually in this case there really is no need to loop thruwindows
.Note that macOS Sierra what the last version in which Terminal supported multiple
tabs
of awindow
programmatically. In other words, from the UI a single window with two tabs there would betab 1 of window 1
andtab 2 of window 1
, but since macOS High Sierra from the UI a single window with two tabs there would betab 1 of window 1
andtab 1 of window 2
, and thus no longer the need to loop thrutabs
.There is all so no need to do something like
set selected of tab j of window i to true
as once a givenwindow
is setfrontmost
, the value oftab 1 of window i
is already set totrue
as a result.The example shell script and AppleScript code, shown above, was tested in Terminal as an executable shell script under macOS Catalina and macOS Big Sur with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.
As we do not know how you have your
zsh
shell script coded, you'll have to work in the code presented herein to suite your needs.