Note: This posting is related to my posting at bash - Reading answer to control string sent to xterm - Stack Overflow , but I could get there a solution only for bash. I can use that solution, but for curiosity, I wonder, whether I could do this in Zsh as well.
The problem is to send a (Posix-) terminal query string to the terminal where the (interactive) shell is running, and to read the response from the terminal. For example, when we send Escape followed by the letter Z, the terminal is supposed to respond with the terminal ID. This response also starts with an Escape, followed by an arbitrary number of characters. Since I don't know the number of characters returned in advance, I have to accumulate them one by one.
This is the solution I achieved with bash, ask_tty.sh:
#!/bin/bash
str='' # Buffer for response
tty=$(tty)
# Send query string to terminal. Example: Esc Z queries for terminal id
echo -e '\e'${1:-Z} >$tty
# Read response from terminal
while :
do
read -rs -t 1 -n 1 <$tty
if [[ -z $REPLY ]]
then
break
fi
str="${str}$REPLY"
done
# Output response without leading Esc
echo "${str#?}"
If I run in my terminal either ask_tty.sh Z or ask_tty.sh (because I made Z the default value), I get as response on stdout
[?63;1;2;4;6;9;15;22;29c
The actual reading of each character is done by read -rs -t 1 -n 1 <$tty.
I feel that for adapting this solution to Zsh, I have to change the bash read to an equivalent Zsh read, but I could not get it done: Either the command hangs, or it returns only the first character of the answer string. For instance, I tried read -rs -t -k and read -rs -t 1 -k 1.
How can I solve this in Zsh?
Update: I'm using Zsh 5.3 (given the evolution of Zsh, version might matter here), running on Cygwin.