Shell script start 1 session with multiple windows

user3578925 picture user3578925 · May 2, 2014 · Viewed 7k times · Source

I am pretty new to shell scripting (you may say I am just starting). What I need is to write a shell script to open ONLY 1 "screen" session. Then I want to open multiple windows (say 10) in the same session and have each session to do something e.g print "hello". So here is a part of my code but it only creates one window (0) and doesn't print anything on that window:

#!/bin/bash
screen-d -m -S mysession
for n in {1..10}; do
    i=$(($n-1))
    screen -S mysession -p $i -X echo "hello"
done

Like I said, my sample code doesn't work! It opens one session with only one window '0', and there is nothing printed on the terminal on window '0'.

Could you please give me some help? The code is supposed to open one screen session and then in the loop to open 10 windows and print "hello" in each window.

Thank you in advance!

Abedin

Answer

ymonad picture ymonad · May 2, 2014

The command you can send with -X option is not shell command but screen command.

Check CUSTOMIZATION section in man screen to see the list of screen command. the following code uses screen command to create new window and stuff command to show text on the window.

#!/bin/bash
screen -d -m -S mysession
# window 0 is created by default, show hello0 on it
screen -S mysession -p 0 -X stuff hello0
for n in {1..9}; do
  # create now window using `screen` command
  screen -S mysession -X screen $n
  screen -S mysession -p $n -X stuff hello$n
done

Now you can attach to myscreen session and check that there are 10 windows and hello0 .. hello9 is displayed in each window.

$ screen -r mysession
[Press C-a "]