6

I would like to send a command to a screen session and if possible get the output.

My attempt at sending a command to a screen session is as I found on this website and lots of others, but it doesn't seem to work:

root@server [~]# screen -X "script -a -c 'ls -l' /tmp/command.log" && cat /tmp/command.log
cat: /tmp/command.log: No such file or directory
root@server [~]# 

Note there is only 1 Screen session running, so I have omitted -S and -p (tried it with those too and no effect). For example:

root@server [~]# screen -p 0 -X stuff "script -a -c 'ls -l' /tmp/command.log" && cat /tmp/command.log
cat: /tmp/command.log: No such file or directory
4

1 Answer 1

4

First, read sending text input to a detached screen. You do need -p to direct the input to the right window. Also, the command won't be executed until you stuff a newline (CR or LF, the interactive shell running inside screen accepts both). That's:

screen -p 0 -X stuff "script -a -c 'ls -l' /tmp/command.log$(printf \\r)" &&
cat /tmp/command.log

There's a second problem, which is that the screen -X stuff … command completes as soon as the input has been fed into the screen session. But it takes a little time to run that script command. When cat /tmp/command.log executes, it's likely that script hasn't finished; it might not even have started yet.

You'll need to make the command running inside screen produce some kind of notification. For example, it could signal back that it's finished, assuming that the shell within Screen is running on the same machine as Screen.

sh -c '
  sleep 99999999 &
  screen -p 0 -X stuff "\
script -a -c \"ls -l\" /tmp/command.log; kill -USR1 $!
"
  wait
  cat /tmp/command.log
'
3
  • That's a workaround and a half! Anyway thank you very much. This does the trick perfectly. Will tick as soon as possible :)
    – James
    Commented Dec 3, 2012 at 0:15
  • How would I go about swapping ls -l for $1?
    – James
    Commented Dec 3, 2012 at 3:14
  • @JamesHadley I don't understand the question. Commented Dec 3, 2012 at 18:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .