Run commands in screen after creating one per bash

跟風遠走 提交于 2020-01-17 05:54:34

问题


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?


回答1:


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:

  • screen options
  • screen commands



回答2:


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).



来源:https://stackoverflow.com/questions/28774681/run-commands-in-screen-after-creating-one-per-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!