This question already has an answer here:

Is it possible to run a command in another opened terminal? I know I can redirect the output of a command in another terminal. For example:

ls >/dev/pts/x

Where x can be obtained by running tty on the target terminal. But the command is executed on the current terminal. That is not what I want.

To clarify my real objective, I want to send a command to every opened terminal, to change color theme without having to re-open every terminal.

marked as duplicate by muru, Archemar, Anthony Geoghegan, schily, RalfFriedl Oct 29 '18 at 17:34

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Did you e.g try cat > /dev/pts/x <<EOF\n $(ls -l)\n EOF ? Where $(ls -l) is in a new line? – Valentin Bajrami Oct 28 '18 at 9:12
  • 3
    This feels like an XY problem. What are you trying to achieve by running a command in a different terminal window? – roaima Oct 28 '18 at 9:18
  • 1
    I want to send a command to every opened terminal, to change color theme without having to re-open every terminal. I may have found a solution by sending an IOCTL to the pts. – DBLouis Oct 28 '18 at 9:21
  • 2
    How do you currently change the color theme of one terminal (the one you're typing to)? – egmont Oct 28 '18 at 10:28
  • 2
    How do you update the color theme? Let's say the command foo updates it for you, by emitting relevant escape sequences. Then foo > /dev/pts/x should work for updating them in another terminal. (The prompt solution might also be a good one.) – egmont Oct 28 '18 at 11:12

You can send color/cursor escapes to a terminal by simply writing to /dev/pts/N or /dev/ttyN; for instance, if /dev/pts/5 is an xterm, you can set its background to red from anywhere with printf %b '\e]11;#ff0000\a' > /dev/pts/5 (of course, you need write permissions to /dev/pts/5).

There is a slim chance that running such a command may badly interract with other escapes sent by the program(s) running in the terminal, but in the worst case this will only result in a scrambled terminal.

For the more general problem of running a program in another terminal/session, the only way I can think that possible is by hijacking a process running in that terminal, and fork+exec the program from inside it. Example:

gdb -p PID -batch -ex 'p system("ls")'

This gets a lot more involved if the program has to read from the terminal; before the exec, the process will have to be added to the foreground process group.

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