1

I've finally gotten ssh onto my phone, but having done so, I realize that some of my ancient hard-coded scripts are very specific to an 80x24 resolution.

I'm aware that $COLUMNS will give me my 80, and allow me to do some things, but I'd like to figure out where I can access the other dimension of the terminal I'm getting to look at.

I'd hate to have to hard-code a set for every terminal, phone, or other hardware I might use, but right now it's looking like that may be the best option.

My phone gives me 53x13 with ConnectBot (couldn't find a better solution?), in case anyone cares.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
user3082
  • 991
  • 2
  • 10
  • 18

2 Answers2

4

The equivalent of $COLUMNS for rows is $LINES. That is set by some shells like zsh or bash (though in the case of bash, only when interactive) based on the tty device line discipline settings (themselves, usually set by the terminal emulator or in the case of ssh, by sshd from values supplied by the client (I don't know if ConnectBot sends those)).

You should be able to find the information in your shell man page. For instance, for zsh: info zsh LINES.

Other options:

  • on some systems (and that will be standard in a future POSIX version), stty size returns the same information as <lines> <columns> on one line. On others, they'll usually show in the output of stty -a though in a format that varies from system to system.
  • With the ncurses implementation of tput, you can use tput lines and tput cols to get the number of lines and columns (which can fall back to querying the terminfo database when the information cannot be retrieved from the terminal device).
  • Some xterm-like terminal emulators (I don't know if that's the case of ConnectBot) let you query the terminal size via some escape sequences (\e[18t). For instance, with zsh:

    IFS=";" read -sd t $'ignore?\e[18t' lines cols
    

    to store the dimensions in $lines and $cols.

  • with most terminals, instead of the \e[18t escape sequence, it's also possible to use (more common) escape sequences that move the cursor to the bottom right corner of the screen and query the cursor position there. That's what the resize utility shipped with xterm actually does and can be used to align the tty settings to that and set $LINES and $COLUMNS environment variables for those shells that don't do it already on their own:

    eval "$(resize -u)"
    
1

stty size outputs the number of rows and columns of the current terminal; to extract the number of rows, keep the first field only:

stty size | cut -d\  -f1
Stephen Kitt
  • 434,908