How to open new Terminal tab and get focus back to the prev tab?

1.4k views Asked by At

I want to run a command in a terminal tab which will open a new tab, run a command there too and then get the focus back to the previous Terminal tab (the one i run the first command), is it possible? using of corse osascript.

what i have so far:

osascript -e 'tell application "Terminal" to activate' -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down'
osascript -e 'tell application "Terminal"' -e 'do script "cd /path/to/dir; clear;" in selected tab of the front window' -e 'end tell' > /dev/null
osascript -e 'tell application "System Events" to tell process "Terminal" to key code "48" using control down' > /dev/null

this will only work if i have only 2 opened tabs.

1

There are 1 answers

4
Charles Srstka On BEST ANSWER

osascript -e 'tell application "Terminal" to set selected of tab 1 of front window to true'

Replace the 1 with the appropriate tab number to select whichever tab you like.

Or you can save the current tab number:

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'