expecttmux

Is it possible to detach a tmux session by sending control sequences using expect?


Consider the following expect script:

spawn bash
expect " \$"
send "tmux\r"
expect " \$"
send "echo hello\r"
send "\x02"
send "d"
interact

I expect this script to create a tmux session, execute "echo hello", and then detach. The first two parts work great, but instead of detaching, I just get the literal characters ^Bd on my terminal.

Is it possible for expect to send the Control-B, d sequence to tmux exactly like what happens if I type it on the keyboard?


Solution

  • I fiddled with this a bit, and empirical evidence suggests that the problem is with tmux rather than expect, but expect can work around it by adding a small delay.

    In particular, it seems that if expect sends the sequence too quickly after the previous command terminated, tmux does not interpret the sequence and echos it instead. Curiously, screen does not have this problem.

    spawn bash
    expect " \$"
    send "tmux\r"
    expect " \$"
    send "echo hello\r"
    
    # Wait for prompt and then sleep a bit. Empirically, waiting for the prompt and not sleeping results in tmux not interpreting the control sequence some of the time.
    expect " \$"
    sleep 0.1
    
    send "\x0b"
    send "d"
    interact