Read the current terminal size from within bash

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.


Advertisement


About fnx

PSN: the_phoenix
This entry was posted in Uncategorized. Bookmark the permalink.

3 Responses to Read the current terminal size from within bash

  1. Neil Padgen says:

    stty -a | head -1 | awk ‘{ print “width=” $4 “\nheight=” $6 }’

  2. fnx says:

    Yes, very clever 🙂

    However, I was more after a general way of being able to parse the multitude of value-returning escape sequences that terminals provide (like mouse position, title, window-size in pixels, etc.).

    And it was prompted by the kit I’m fiddling with at work that has to be configured to boot with a serial console; for some reason, on one flavour of hardware, “stty -a” is returning cols & rows = 0, which screws the display when the PuTTY window I’m using to get at it is large (keeps dropping to a presumed 80×24).

    Part of my investigation is going to be probing what support PuTTY has for reporting its window size & settings so I can see where the issue is, or at least try to recover from it. Hence reading the raw codes.

    So I’m not a complete dunderhead!

  3. volnt says:

    tput cols
    tput lines

    Works great too 🙂

Leave a Reply to fnx Cancel reply

Your email address will not be published. Required fields are marked *

*