Shell – What’s the name of the environment(?) variable with current terminal width

shellshell-script

I know this is something simple, but I can't recall where it's located/named.

Where's the variable for the current width of the terminal stored?

I see this answer talks about changing things:
How are terminal length and width forwarded over SSH and telnet?

But I'd like to get the current value, for use in a script (and I don't understand everything in that answer).

Once upon a time I recall there was some way to display all environment variables? (Hmm, I see an answer that says use set (vs. env), but my set only shows LINES and not width?)


Then of course it's onto the next problem; once I have that $number I'd like to repeat a character ( "-" ) that many times, to make a dashed line that's X-characters-wide (fills the terminal, without wrapping). If you've got an elegant way I should be doing that, I'd appreciate that too.

Best Answer

STTY SIZE

The canonical way is to ask the terminal about its actual size, when you want to know it

stty size

prints ROWS COLUMNS.

Print a dashed line

About your second question, seq is your friend

stty size|if read rows cols
then for x in `seq $cols`
do printf "-"
done fi

or per awk loop

stty size|awk '{ ORS="-"; n=$2; for (i=0; i<n; ++i) { print ""; } }'

.

Set a line variable

But actually it would be better to save our line in a variable

eval $(L=""; stty size|if read r c
    then for x in `seq $c`
    do L="${L}-"
    done
    echo L="$L"
    fi
)

Trap on SIGWINCH

As long as we don't need to recalculate the terminal size

trap 'echo "recalculate L"' SIGWINCH

we can now use $L to print the line. Of course you can autotune your $L variable on SIGWINCH:

trap 'eval $(L=""; stty size|if read r c
    then for x in `seq $c`
    do L="${L}-"
    done
    echo L="$L"
    fi
)' SIGWINCH

. In a terminal where you set up, such a trap you can just say

echo $L

and you are done.