Apologies in advance if this has already been asked – it’s really hard to search for this as bash and terminal show up together in so many places.
Basically what I’d like to be able to do is have a bash script be aware of whether or not the terminal it’s running in is currently active (selected) so that I could use notify-send to inform the user something has completed only if it’s not currently the active window. I’m guessing it would be possible to do something that can at least detect whether the active window is a terminal window by accessing gnome somehow, but I have no idea how and I imagine it would likely be a hack, but any help would be appreciated.
After some more digging I’ve found a workable solution so I’m going to post it as an answer, but it’s not very portable so I’d still appreciate any better solutions.
What I’ve found is that when using Gnome you have access to a $WINDOWID variable from the gnome-terminal (this doesn’t work if you’ve ssh’ed to another box unfortunately and so isn’t ideal). This can be combined with xprop like this:
Which can then be compared for equality. A more suitable way of getting the current window id would be good however.
Edit: Having seen Zaytzev’s answer I guess this could be combined so instead of using $WINDOWID I could set the terminal title and check whether
xprop -id $activeWindow WM_NAMEis equal to my window title.