Debian – How to start new window in the same screen session automatically

bashdebiandisplaygnu-screen

I read How can I start multiple screen sessions automatically?, but I don't understand the first accepted reply:

screen -dmS "$SESSION_NAME" "$COMMAND" "$ARGUMENTS"

In my case I need to automatically create one screen session for one script, and afterwards I need to create a new window in the same session for another script. Manually, I would:

  1. run screen
  2. enter command
  3. CTRL+A
  4. CTRL+C
  5. enter command
  6. CTRL+A
  7. CTRL+D

How can I do this automatically in a script? A simple example would help me a lot.

Thank you for replies.

Best Answer

I'm not exactly sure what you want to happen - do you want a script that creates the screen session with two windows for two commands, or do you want to run a script in a screen window that runs one command, then creates a new window for the second one?

The second one's easy, so let's start with that:

#!/bin/bash
command1
screen command2

Running "screen " within screen will create a new window in the current session, not start a new one. But it will return immediately, so after the last line there, the script will exit while command2 is still running. And when command2 is done, its window will close.

The first interpretation of your question a bit harder anyway, so let's go ahead and solve the above while at it:

#!/bin/bash

# Need to positively identify the session name:
SESSION=mysession.$$
echo "TO ATTACH TO SESSION: screen -r ${SESSION}"

# For signalling and stuff
FLAGDIR=$(mktemp -d)

# To keep the windows around after the commands are done,
# set the "zombie" option (see the man-page)
echo "source $HOME/.screenrc" > ${FLAGDIR}/screenrc
echo "zombie xy" >> ${FLAGDIR}/screenrc

# Use that temporary screenrc; create a detached session:
screen \
    -c ${FLAGDIR}/screenrc \
    -d -m \
    -S ${SESSION} \
    bash -c "command1 ; touch ${FLAGDIR}/done"

# Wait for command1 to terminate
while [[ ! -f ${FLAGDIR}/done ]] ; do sleep 1 ; done

# Now start command2 in a new window, by sending a remote command:
screen -S $SESSION -X screen command2

# Don't need this any more:
rm -rf ${FLAGDIR}

The script will launch command1, wait until it's done, then launch command2and exit. As if you'd run command1 ; command2 &, but with the output elsewhere. I'm sure you can figure out how to run command1 in the background.

Related Question