22

Is there any command that I can use to send input or commands to a given tmux session / pane without connecting to it?

It's for unattended access,

I've a console application running on a tmux session. I want to restart it when a deploy (using capistrano) is done.

Is it possible?

Basically I want to send:

exit
cd ..
cd app
rails console

1 Answer 1

30

This question has a solution on ServerFault:

It uses the send-keys command, which is documented in the man-pages:

The following is a "Hello World" example illustrating the use of the send-keys command.

  • Step 1. Create a detached session:

    user@host:~$ tmux new -d -s mySession
    
  • Step 2: Execute a command in the detached session:

    user@host:$ tmux send-keys -t mySession.0 "echo 'Hello World'" ENTER
    
  • Step 3: Attach to the session:

    user@host:$ tmux a -t mySession
    

You should see the following text displayed in the Tmux terminal window:

user@host:$ echo 'Hello World'
Hello World

user@host:$

This demonstrates that the echo command was successfully sent and executed inside of the tmux session.

An adaptation of this technique to your commands might look something like the following:

user@host:~$ tmux send-keys -t mySession.0 exit ENTER
user@host:~$ tmux send-keys -t mySession.0 "cd .." ENTER
user@host:~$ tmux send-keys -t mySession.0 "cd app" ENTER
user@host:~$ tmux send-keys -t mySession.0 "rails console" ENTER
5
  • 1
    what if something is half written in the tmux terminal. How can I clear the terminal before running tmux send-keys -t mySession.0 "echo 'Hello World'" ENTER Jul 30, 2020 at 9:23
  • 2
    @blueray I guess you could send "Ctrl + c" to clear the current line: tmux send-keys C-c. That would probably work.
    – igal
    Jul 30, 2020 at 11:24
  • Make sure if you use sudo to create your tmux session that you also call send-keys/send with sudo sudo tmux send ... otherwise the command doesn't do anything nor throw an error. Jun 16, 2022 at 21:04
  • If you call tmux send-keys over ssh, you'll need to escape spaces twice: once for ssh, and another time for tmux, like so: ssh <host> tmux send-keys -t mySession.0 'echo\ hello' ENTER Mar 17 at 14:48
  • Or, as I just realised, escape the quotes: ssh <host> tmux send-keys -t mySession.0 \'echo hello\' ENTER. Mar 17 at 14: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.