1

Is there any way to make a bash script enter a certain keystroke? What I'm trying to accomplish here is a script that will run Ctrl+B to exit tmux.

EDIT: I see that several people are saying that it's better to use a program - specific command. What if I wanted to edit a text file (in this case the bash_aliases file) using a bash script?

5

If you want to interact with tmux in a script, that's where you want to use tmux ... tmux-command. Like:

tmux kill-session

To exit the current session.

tmux kill-server

To exit the server (kills all sessions).

tmux detach-client

to detach a client (exit, but you can reattach later).

  • I'm using SSH with tmux; when I run tmux kill-session, would it kill my end, or the Raspberry Pi's (what I'm SSH'ing to) end? – evamvid Feb 1 '14 at 17:17
  • @evamvid, tmux talks to the tmux server via a unix domain socket (whose path is in $TMUX), so it can only talk to a tmux server on the same machine, so a process can only kill the tmux session that is running on the same machine. – Stéphane Chazelas Feb 1 '14 at 18:58
4

You can use xdotool to send keystrokes, if really necessary.

xdotool search "Konsole" windowactivate --sync key --clearmodifiers ctrl+b
2

To answer the question in the title.

The way to simulate a key press in a terminal is via the TIOCSTI

For instance:

insert() {
  perl -le 'require "sys/ioctl.ph";
            ioctl(STDIN, &TIOCSTI, $_) or
              die "$!\n" for split "", join " ", @ARGV' "$@"
}

However, in the case of tmux, if you do:

insert $'\02'

within a tmux pane, that will insert the ^B character in the input buffer of the terminal of that pane, not any of the terminals attached to the current session tmux is reading its input from.

The solution would be to do:

insert $'\02' < "$(tmux lsc -F '#{client_tty}' -t '' | head -n 1)"

Where:

tmux lsc -F '#{client_tty}' -t ''

reports the terminal(s) attached to the running session.

But on modern Linux systems, that won't work (you'll get a Operation not permitted error) because, for security reasons, the TIOCSTI ioctl can only be issued to your controlling terminal (and the controlling terminal of a shell interpreting a script in a tmux pane would be the pane's terminal).

You'd have to ask tmux to do that, and I'm not sure that is possible.

1

You can easily close tmux by executing:

pkill -term tmux

This will send tmux: "Please close yourself"

0

Another useful *NIX tool for automating interactions with terminal programs is Expect:

http://www.nist.gov/el/msid/expect.cfm

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.