Luca Steeb
Luca Steeb

Reputation: 1859

Run commands in screen after creating one per bash

I have the following bash file which should create a screen, go to a directory and then start a node script:

screen -S shared     // 1
cd /home/nodejsapp   // 2
node start.js app.js // 3

The problem is, after executing 1, I indeed see the screen 'shared', but 2 & 3 will execute on the previous terminal, not on the screen 'shared'.

How can I achieve that commands 2 and 3 will be executed on the current screen?

Upvotes: 0

Views: 1814

Answers (2)

pynexj
pynexj

Reputation: 20797

You may create a detached screen and then send commands to it. For example:

screen -d -m -S shared
screen -S shared -X -p 0 stuff $'cd /home/nodejsapp\n'
screen -S shared -X -p 0 stuff $'node start.js app.js\n'

If you need to attach to the screen session afterwards, then you can add one more line:

screen -S shared -r

See screen's manual for more details:

Upvotes: 4

Thomas Dickey
Thomas Dickey

Reputation: 54583

You could run a "server" as the program within screen, which reads commands to execute from the pseudoterminal which the "tty" program identifies. For instance, as I'm writing this, tty says (inside screen)

/dev/pts/2

and I can write to it by

date >/dev/pts/2

On the server side, the script would read line-by-line in a loop from the same device. (On some other systems, there are differently-named devices for each side of the pseudoterminal).

That only needs a script which starts by getting the output of "tty", writing that to a file (which a corresponding client would know of), and then the client would read commands (whether from the keyboard or a file), write them to the server via the pty device.

That's doable with just a couple of shell scripts (a little more lengthy though than the usual answer here).

Upvotes: 0

Related Questions