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:

  1. #!/bin/bash
  2.  
  3. # Request size
  4. stty -echo
  5. echo -ne '\e[18t'
  6.  
  7. # Read size char. by char. (CSI 8 ; height ; width t)
  8. width=
  9. heigh=
  10. p=0
  11. while IFS= read -r -n1 char
  12. do
  13. # Get past CSI
  14. if [[ "$p" == 0  &&  "$char" == ";" ]]then
  15. p=$((p+1))
  16.  
  17. # width
  18. elif [[ "$p" == 1  ]]then
  19. [[ "$char" == ";" ]]  &&  p=$((p+1))  ||  height="${height}${char}"
  20.  
  21. # height
  22. elif [[ "$p" == 2  ]]then
  23. [[ "$char" == "t" ]]  &&  break  ||  width="${width}${char}"
  24.  
  25. fi
  26. done
  27.  
  28. # Done
  29. stty echo
  30. 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

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

*