Getting console width using a bash script

The tput command is an excellent tool, but unfortunately it can't retrieve the actual settings for an arbitrarily selected terminal.

The reason for this is that it reads stdout for the terminal characteristics, and this is also where it writes its answer. So the moment you try to capture the output of tput cols you have also removed the source of its information.

Fortunately, stty reads stdin rather than stdout for its determination of the terminal characteristics, so this is how you can retrieve the size information you need:

columns=$(stty -a <"$terminal" | grep -Po '(?<=columns )\d+')
rows=$(stty -a <"$terminal" | grep -Po '(?<=rows )\d+')

By the way, it's unnecessarily cumbersome to write this as echo $(/usr/bin/tput cols).

For any construct echo $(some_command) you are running some_command and capturing its output, which you then pass to echo to output. In almost every situation you can imagine you might as well have just run some_command and let it deliver its output directly. It's more efficient and also easier to read.

tput cols and tput lines query the size of the terminal (from the terminal device driver, not the terminal itself) from the terminal device on its stdout, and if stdout is not a terminal device like in the case of cols=$(tput cols) where it's then a pipe, from stderr.

So, to retrieve the values from an arbitrary terminal device, you need to open that device on the stderr of tput:

{ cols=$(tput cols) rows=$(tput lines); } 2< "$TERMINALPATH"

(here open in read-only mode so tput doesn't output its error messages there).

Alternatively, you may be able to use stty size. stty queries the terminal on stdin:

read rows cols < <(stty size < "$TERMINALPATH")

None of those are standard so may (and in practice will) not work on all systems. It should be fairly portable to GNU/Linux systems though.

The addition of stty size or other method to query terminal size was requested to POSIX but the discussion doesn't seem to be going anywhere.

This script:


echo "The number of columns are $COLUMNS"
echo "The number of lines are $LINES"

Worked here with absolutely nothing more.....

Why you are setting a environment variable with data?


Are you try to get the columns and lines from other script or tty? Is that it? Still strange for me because you're setting the columns environment variable for the local script....