What's the best way to run a command inside a screen session such that its parent shell can be accessed? I want to be able to restart it from within the same screen session.

The best I've managed to come up with is the following:

$ cat mr-t.sh 

exec /bin/bash

and then:

screen -e'^\\\' -S top-in-screen ./mr-t.sh

Then, if top stops running, I'll at least get a new shell within the same screen session I can work with. This isn't very elegant, though, and I can't quite convince myself that the signal will reliably be sent to the right process if I hit C-c. Moreover, C-z doesn't work at all.

I'm using bash 3.2.48 on OSX and 3.2.39 on Linux. Both are probably patched by OS vendors.

There's nothing special about the top command here, of course.

[As an aside, -e'^\\\' reassigns the Magick Screen Key from C-a (a bad default if there ever was one) to C-\.]

  • What is wrong with just starting top from the shell?
    – vonbrand
    Feb 10, 2013 at 1:58
  • @vonbrand Is that a serious question? Do you really think I'm running top? More to the point, can you really think of no use cases for wanting to automate starting a long-running program in a manner that makes debugging problems easy? Jan 8, 2014 at 20:54

3 Answers 3


Create a ~/.screenrc.top like so:

stuff "top\015"

Now run screen -c ~/.screenrc.top. No race condition!


Here's an imperfect solution I found.

screen -e'^\\\' -dmS top-in-screen

Then you can run:

screen -S top-in-screen -p 0 -X stuff 'top^M'

(Note that although you'll only see ^M you should actually type C-v followed immediately by C-m.)

It's imperfect because (I think) there is a race condition between the first and second invocations of screen.

From http://aperiodic.net/screen/faq#how_to_send_a_command_to_a_window_in_a_running_screen_session_from_the_commandline, which has lots of other good information as well.


Since asking this question, I've adopted a different but much more effective solution: use tmux.

Start a new named, detached session:

$ tmux new -d -s top

Send a command to its zeroth window.

$ tmux send-keys -t top:0 "top" C-m

C-m is equivalent to hitting return. Often it's what you want; sometimes you'll want to leave it out.

tmux' command set is well-documented. So it's easy to write far more complicated scripts to drive it.

Normally this would be an extremely obnoxious answer, but since it's my question I'll allow myself some leeway, especially since I never really got any of the other methods to work reliably. In contrast, I was able to script tmux correctly the first time I tried to.

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.