views:

141

answers:

3

Consider the following:

me@mine:~$ cat a.sh 
#!/bin/bash
echo "Lines: " $LINES
echo "Columns: " $COLUMNS
me@mine:~$ ./a.sh 
Lines: 
Columns: 
me@mine:~$ echo "Lines: " $LINES
Lines:  52
me@mine:~$ echo "Columns: " $COLUMNS
Columns:  157
me@mine:~$

The variables $LINES and $COLUMNS are shell variables, not environmental variables, and thus are not exported to the child process (but they are automatically updated when I resize the xterm window, even when logged in via ssh from a remote location). Is there a way in which I can let my script know the current terminal size?

EDIT: I need this as a workaround do this problem: vi (as well as vim, less, and similar commands) messes up the screen every time I use it. Changing the terminal is not an option, and thus I'm looking for workarounds (scrolling down $LINES lines surely is not the perfect solution, but at least is better than losing the previous screen)

+1  A: 

Have you tried making your shebang say:

#!/bin/bash -i
Dennis Williamson
Also, see my answer to the question you referenced. Setting the `t_ti` variable to null may help with `vim`. http://stackoverflow.com/questions/630519/can-you-make-vi-advance-the-screen-when-opened/1780630#1780630
Dennis Williamson
Unfortunately, `#!/bin/bash -i` does not make **any** difference neither in AIX nor in linux
Davide
I get blank output from your script without the `-i` and correct numbers with it. This is on Ubuntu (LINES and COLUMNS are not exported). I found that on Cygwin, I had to export the two variables (you could do this in ~/.bashrc) in order to get it to work and the `-i` wasn't needed. However, I had to do `kill -SIGWINCH $$` at the Bash prompt to get the values to update if I resized the window (for Cygwin).
Dennis Williamson
Ubuntu what? On Hardy Haron, `-i` does not make any difference: blank output with or without it (anyway, I need this on AIX, not Ubuntu)
Davide
It's a Bash thing. It shouldn't be an OS thing (unless SIGWINCH isn't getting sent). I've tested this on Bash 3.2 and 4.0.
Dennis Williamson
+3  A: 

You could get the lines and columns from tput

#!/bin/bash

lines=$(tput lines)
columns=$(tput cols)

echo "Lines: " $lines
echo "Columns: " $columns
Puppe
great, thanks! (please ignore these other spare character to make SO happy about the length of my comment)
Davide
+1  A: 

$LINES and $COLUMNS in bash is just a shell-y wrapper around the TTY ioctls giving you the size of the TTY and the signals sent by the terminal every time that size changes.

You could write a program in some other language which calls those ioctls directly to get to the TTY dimensions, and then use that program.

EDIT: Well, turns out that program already exists, and is called tput. Vote up Puppe's tput based answer.

ndim