I have seen many questions about how to set the tab (or window) name, but how to get it? I have setup terminal to open 8 tabs, each tab having its own name (dev1, dev2, ... dev8) Is there any way for a shell script to identify in which tab it is (read the tab's name?)
3 Answers
If all else fails, then AppleScript to the rescue:
title=`osascript -e 'tell application "Terminal" to get name of front window'`
echo $title
Beware though when using of front window
when using multiple windows. This will print the wrong results when switching to another tab in 5 seconds:
sleep 5; osascript -e 'tell application "Terminal" to get name of front window'
(So I hope someone can give you an easier way.)
-
In general, when scripting the Terminal application from inside a terminal, you should get the current tty device and search for the window that corresponds to that. e.g., you can get the tty device pathname via the
tty
command. Oct 4, 2018 at 1:34
This works on my Fedora box, but I don't have a Mac to verify:
xprop -id $WINDOWID | grep '^WM_NAME(STRING)' | cut -d\" -f2
-
1
-
xprop
is part of the X window system, which is no longer installed with macOS. In any case, it wouldn’t help here, since Terminal is not an X application. Oct 4, 2018 at 1:36
There is a control sequence for requesting the window title, which corresponds to the sequence for setting the title; however, it is not supported by Terminal, and it is disabled by default in XTerm (and I assume other terminal emulators) for security/privacy reasons.
The XTerm documentation for the control sequences to set/get the window title:
http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Operating-System-Commands
Using application scripting as in Arjan’s answer works, but only when the remote program is on the same computer, and, unlike the control sequence, scripting has security rules, like requiring authentication if the sender and receiver processes don’t have the same owner/user.