I’ve long wondered about a clean way to read terminal (xterm) escape sequence responses, especially from script/the command line. I’ve just come across a need to query the terminal size, and so it was time to go digging.Turns out it’s not too tricky, and the only clever bits are read‘s ability to do character-by-character reads, and using stty to stop the response from being echoed.
get-term-size:
#!/bin/bash # Request size stty -echo echo -ne '\e[18t' # Read size char. by char. (CSI 8 ; height ; width t) width= heigh= p=0 while IFS= read -r -n1 char do # Get past CSI if [[ "$p" == 0 && "$char" == ";" ]]; then p=$((p+1)) # width elif [[ "$p" == 1 ]]; then [[ "$char" == ";" ]] && p=$((p+1)) || height="${height}${char}" # height elif [[ "$p" == 2 ]]; then [[ "$char" == "t" ]] && break || width="${width}${char}" fi done # Done stty echo echo -e "width=$width\nheight=$height"
OK, there’s probably a cleaner way of looping through the characters, but it works.
Leave a Reply to fnx Cancel reply