Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GNU Screen: How can I create a screen in the background if it doesn't exist?

"screen -R -D -S test" will create a session named test if it doesn't exist, or connect to it if it does

"screen -d -m -S test" will create a new detached session named test, whether it exists or not, possibly leading to multiple sessions named test:

There are several suitable screens on:
    9705.test   (06/18/2012 06:42:58 PM)    (Detached)
    9639.test   (06/18/2012 06:42:57 PM)    (Detached)

How can I create a detached session named test, but only if one doesn't already exist?

like image 779
Thomas Johnson Avatar asked Jun 18 '12 23:06

Thomas Johnson


1 Answers

I believe you're looking for the -d -R combination:

screen -d -R -S test

From man screen:

      -d -R   Reattach a session and if necessary detach or  even  create  it
              first

EDIT

If you just want to create a background screen only if it doesn't exist, a little shell function in your ~/.bashrc or ~/.zshrc will work:

function bgsc { 
  if screen -list | awk '{print $1}' | grep -q "$1$"; then
    echo "screen $1 already exists" > &2
  else
    screen -d -m -S $1
  fi
}

Then just call bgsc test.

like image 176
jmdeldin Avatar answered Oct 26 '22 12:10

jmdeldin