Getting the window width
Make a global variable $termsize track the size of the terminal window:
settermsize() {
termsize="$(stty size 2>/dev/null)" && [ "$termsize" ] ||
termsize='25 80'
}
trap settermsize WINCH
settermsize
If stty size fails, the above code assumes that the terminals 80 columns wide and 25 lines high. POSIX does not mandate the size operand for stty, so the fallback is needed.
You can then access the columns argument by using the shell's string substitution capabilities:
echo "${termsize% *}" # Prints the terminal's height.
echo "${termsize#* }" # Prints the terminal's width.
Of course, the scripting language you use likely offers a library that takes care of that for you -- and you should use it.
Printing a line
Once you know the width of the terminal, printing a horizontal line is easy, for example, by abusing printf's string padding:
printf '%*s\n' "${termsize#* }" '' |
tr ' ' -
The first line tells printf to print as many spaces as there are columns (by abusing string padding) to a pipe.
The second line tells tr to read from that pipe and replace every space with a hyphen.