LINES and COLUMNS environmental variables lost in a script

BashShellTerminalEnvironment Variables

Bash Problem Overview


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)

Bash Solutions


Solution 1 - Bash

You could get the lines and columns from tput:

#!/bin/bash

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

echo "Lines: " $lines
echo "Columns: " $columns

Solution 2 - Bash

Because this question is popular, I want to add a newer answer with a bit of additional information.

Often, on modern systems, the $COLUMNS and $LINES variables are not environment variables. The shell sets these values dynamically after each command and we usually cannot access them from non-interactive scripts. Some programs respect these values if we export them, but this behavior isn't standardized or universally supported.

Bash sets these variables in the scope of the process (not the environment) when we enable the checkwinsize option using:

shopt -s checkwinsize 

Many systems enable this option for us in a default or system-wide startup file (/etc/bashrc or similar), so we need to remember that these variables may not always be available. On some systems, such as Cygwin, this option is not enabled for us, so Bash doesn't set $COLUMNS and $LINES unless we execute the line above or add it to our ~/.bashrc.

Portable Approaches

When writing non-interactive scripts, we usually don't want to rely on $LINES and $COLUMNS by default (but we can check these to allow a user to override the terminal size manually if desired).

Instead, the stty and tput utilities provide portable means to determine the terminal size from a script (the commands described below are currently undergoing standardization for POSIX).

As shown in the accepted answer by Puppe, we can use tput to gather the terminal size in a pretty straightforward manner:

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

Alternatively, the size query for stty gives us the number of terminal rows and columns in one step (output as the number of lines followed by two spaces followed by the number of columns):

size=$(stty size)  # "40  80" for example 

The stty program usually ships with GNU Coreutils, so we can often find it on systems without tput. I sometimes prefer the stty approach because we invoke one fewer command and subshell (expensive on Cygwin), but it does require that we parse the output into rows and columns, which may be less readable:

lines=${size% *}
columns=${size#* }

Both of the approaches described above work in any POSIX shell.

Non-portable Approaches

If we don't care about portability, Bash supports process substitution to simplify the previous example:

read lines columns < <(stty size) 

...which runs faster than the tput example, but still slower than the first stty implementation, at least on my machine. In practice, the performance impact is probably negligible—choose the approach that works best for the program (or based on which command is available on the target system).

For Bash versions 4.3 and later, we can exploit the checkwinsize option to avoid a dependency on an another program. When we enable this option in a script, Bash will set $LINES and $COLUMNS like it does for an interactive prompt after a child process exits:

#!/bin/bash
shopt -s checkwinsize
cat /dev/null # Refresh LINES and COLUMNS

...like when a subshell exits:

shopt -s checkwinsize
(: Refresh LINES and COLUMNS)

Bash fetches the terminal size after every external command invocation if we enable this option, so we may want to turn it back off after initializing the variables:

shopt -u checkwinsize

If, for some reason, we still want to use $LINES and $COLUMNS from the environment in our scripts, we can configure Bash to export these variables to the environment:

trap 'export LINES COLUMNS' DEBUG

The Bash DEBUG trap executes before each command entered at the prompt, so we can use it to export these variables. By re-exporting them with each command, we ensure that the environment variables remain up-to-date if the terminal size changes. Add this line to .bashrc along with the checkwinsize option shown above. It works fine for personal scripts, but I don't recommend using these variables in any script that will be shared.

Solution 3 - Bash

eval $( resize )

does that job...(on xterm-based terminal)

Solution 4 - Bash

kill -s WINCH $$

does set the variables.

Solution 5 - Bash

For the sake of completion, let me mention that setting the 'checkwinsize' option is exactly what the OP is looking for, but there is a catch. It is by default unset in non-interactive scripts, but you can elect to add the following line at the beginning of any script to enable it :

shopt -s checkwinsize

Unfortunately, the LINES and COLUMNS variables are not set immediately upon setting the option (at least the last time I tried). Instead, you need to force Bash to wait for a subshell to complete, at which point it will set those variables. The full Bash-only solution to this problem is thus to start your script with the following line :

shopt -s checkwinsize; (:;:)

You can then use the LINES and COLUMNS variables to your heart's content, and they will be reset to the correct values each time the terminal is resized, without needing to call any external utilities.

Solution 6 - Bash

Have you tried making your shebang say:

#!/bin/bash -i

Solution 7 - Bash

Running help export might help?

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:~$ export LINES COLUMNS
me@mine:~$ ./a.sh 
Lines:  52
Columns:  157
me@mine:~$ 

Solution 8 - Bash

$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.

Solution 9 - Bash

#!/bin/bash -i

-i works now with bash 4.2.10(1)-release on Ubuntu 11.10.

$ cat show_dimensions.sh 
#!/bin/bash -i
printf "COLUMNS = %d\n" $COLUMNS
printf "LINES = %d\n" $LINES

$ ./show_dimensions.sh 
COLUMNS = 150
LINES = 101

$ bash --version
GNU bash, version 4.2.10(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

The numbers do change with a window resize; a trap reveals the script is getting a SIGWINCH.

Solution 10 - Bash

Why not use enviroment variables on exec command like this:

docker exec -ti -e LINES=$LINES -e COLUMNS=$COLUMNS  container /bin/bash

Solution 11 - Bash

My experince that you should start the script by the '. script_to_run' form, instead of the 'scritp_to_run'. A simple check as follows:

'(( ${#COLUMNS} )) || { echo "Try start like '. name'" ; return 1 ; }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavideView Question on Stackoverflow
Solution 1 - BashPuppeView Answer on Stackoverflow
Solution 2 - BashCy RossignolView Answer on Stackoverflow
Solution 3 - BashAnthonyView Answer on Stackoverflow
Solution 4 - BasheloView Answer on Stackoverflow
Solution 5 - BashMarc CoiffierView Answer on Stackoverflow
Solution 6 - BashDennis WilliamsonView Answer on Stackoverflow
Solution 7 - BashSwordFishView Answer on Stackoverflow
Solution 8 - BashndimView Answer on Stackoverflow
Solution 9 - BashSegankuView Answer on Stackoverflow
Solution 10 - BashClasssicView Answer on Stackoverflow
Solution 11 - BashapexikView Answer on Stackoverflow