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

1 Answer 1


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 $!
  cat /tmp/command.log
  • That's a workaround and a half! Anyway thank you very much. This does the trick perfectly. Will tick as soon as possible :)
    – James
    Dec 3, 2012 at 0:15
  • How would I go about swapping ls -l for $1?
    – James
    Dec 3, 2012 at 3:14
  • @JamesHadley I don't understand the question. Dec 3, 2012 at 18:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.