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
AdminBee
  • 21,637
  • 21
  • 47
  • 71
Arnold Roa
  • 369
  • 1
  • 3
  • 7

1 Answers1

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
igal
  • 9,666
  • 1
  • 42
  • 58
  • 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` – Ahmad Ismail Jul 30 '20 at 09: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 '20 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. – Chris Smith Jun 16 '22 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 tmux send-keys -t mySession.0 'echo\ hello' ENTER` – Theoretical Economist Mar 17 '23 at 14:48
  • Or, as I just realised, escape the quotes: `ssh tmux send-keys -t mySession.0 \'echo hello\' ENTER`. – Theoretical Economist Mar 17 '23 at 14:50