How do I detect whether my terminal has focus in the GUI from a shell script?

There's a FocusIn/FocusOut mode. To enable:

echo -ne '\e[?1004h'

To disable:

echo -ne '\e[?1004l'

On each focus event, you receive either \e[I (in) or \e[O (out) from the input stream.

GNOME Terminal (and other VTE based terminals) also report the current state when you enable this mode. That is, you can enable and then immediately disable it for querying the value once.

You can combine read with a timeout, or specifying to read 3 characters to get the response. Note however that it's subject to race condition, e.g. in case you have typed ahead certain characters.