GNU screen, how to get current sessionname programmatically

Solution 1:

could you try this one;

screen -d -r $(ps -o ppid -p $$ --no-headers) -X sessionname newsessionname

Solution 2:

It appears that when you set the sessionname manually screen changes the name of the relevant file in /var/run/screen/S-$USER/ but doesn't update the value of $STY which would be ideal.

We can still use the original value of $STY to get the current session's name though as $STY contains the PID that relates to this sessionname.

PID=$(echo $STY | awk -F"." '{ print $1}')

You can then use the PID to get the sessionname from /var/run/screen/S-$USER

SESSIONNAME=$( ls /var/run/screen/S-$USER/$PID* | awk -F"." '{print $2}' )

Now you have the sessionname in SESSIONNAME you can do what you want with it.