how to include screen's session name in hardstatus?

I use different screen sessions for different projects. Starting screen like screen -S project1. Now, I'd like to mention 'project1' in hardstatus line.

Session name can be obtained from environment variable STY: STY=13539.project1.
But how to get this into screen? I've tried backtick command and %` in hardstatus, but I can't seem to get it right.

What I did:

.screenrc:

hardstatus string '%H:%`'
backtick 0 30 30 echo $STY

no luck, empty %`.

backtick 0 30 30 sessionname

still no luck, sessionname: Not found


Solution 1:

You can include this string (with additional information, if desired) in your $PS1:

\[\e]0;$STY\007

inside single quotes in order to delay evaluation of the variable. Then add this to your ~/.screenrc:

hardstatus string '%H:%h'

Unfortunately, screen doesn't set $STY in the environment of the commands it spawns for the backtick feature.

Another option, instead of the one above:

hardstatus string '%H:%`'
backtick 0 30 30 sh -c 'screen -ls | grep --color=no -o "$PPID[^[:space:]]*"'

The advantage of this one is that it follows changes made by using the sessionname command. The first option doesn't.

Edit:

From here:

Since $STY is not set yet when screen sources .screenrc, you can use this trick in your .screenrc:

    screen 
    screen $SHELL -c 'screen -X caption always "$STY"' 

I.e. send a screen command to the first window.

Solution 2:

For me this easily works with inserting %S in the hardstatus.

MWE (.screenrc):

hardstatus on
hardstatus alwayslastline
hardstatus string "%S"

However, this displays the session name without the ID (like ${STY#*.}); in your example: project1.

(Same answer to other questions here and here for completeness).