Gnu-Screen: Run script that sends commands to the screen session it is being run in

From the screen manpage:

  -X   Send the specified command to a running screen  session.  You  can
       use  the  -d or -r option to tell screen to look only for attached
       or detached screen sessions. Note that this command  doesn't  work
       if the session is password protected.

Basically, run

screen -X title mynewtitle
screen -X monitor on

If the terminal is not running within screen, it silently errors:

notinscreen:~$ screen -X title mynewtitle
notinscreen:~$

You can also send the command to a specific session, even while detached. Given a screen session named "main":

$ screen -S main
[detach from screen session]
$ screen -ls
There is a screen on:
        2073.main       (Detached)
1 Socket in /tmp/uscreens/S-dbr.

..you can sent the title of the last-active window to blah:

$ screen -x main -X title blah

..or a specific window (named oldwindow in this example):

$ screen -x main -p oldwindow -X title blah

Instead of using -x main you can use the process ID (from screen -ls), also instead of using a window name (-p oldwindow) you can use a window number:

$ screen -x 2073 -p 0 -X title h

If there is only one session, you do not have to specify the session PID or name.


I think this works:

if [-n "$STY"]; then
    screen -X title "foo"
    screen -X monitor on
fi

Screen declares $STY environment variable, you can try use it.