Bash – How to attach gnu screen without knowing tty number

bashgnu-screen

After starting multiple gnu screen sessions with

screen -S name1
screen -S name2

I would like to selectively attach to them. If I do

screen -D -R name1

it will not attach but instead print:

There are several suitable screens on:
    6799.name1        (08.02.2013 15:47:23)   (Detached)
    3661.name2        (08.02.2013 13:43:25)   (Detached)
Type "screen [-d] -r [pid.]tty.host" to resume one of them.

It works obviously if I type:

screen -D -R 6799.name1

But I would like to attach without knowing the tty number, because I want to start the screen sessions by a script which takes the name as argument. Not knowing the tty number at this time I would need to copy by hand this number whenever I want to reattach later.

An obvious solution would be to extract the tty number from the above screen output using string operations. But that seems a little awkward. Is there a way to tell screen to attach to a specific named session, whatever the tty number is?

Note that I tried the different [-d|-D] [-r|-R] combinations mentioned in the man pages.


Note added:

I create the separate screen sessions in a script using ssh with

ssh -t ${host} "
    screen -S \"$exefile\" -t \"$exefile\" -R "nice -n$prio \"$exefile\" ${exeparams[@]}"; 
    exit 0";

Later I try to connect using

ssh -t ${host} "
    screen -D -R -S \"$exefile\" && 
    echo \"finished.\"; 
    exit";

where $exefile is the name of the executable and the screen session I want to connect to.

Best Answer

Because I am the only one connecting to my screen sessions, and sometimes I want more than one console connected (a la multi display mode) to a session at a time, I use the -x switch.

# screen -S hosts
# screen -ls
  There is a screen on:
      12828.hosts     (Detached)
  1 Socket in /var/run/screen/S-uther.
# screen -x hosts

From man 1 screen

   -x   Attach  to a not detached screen session. 
       (Multi display mode).Screen refuses to attach 
       from within itself.  But when cascading multiple 
       screens, loops are  not  detected; take care.
Related Question