English 中文(简体)
LINES and COLUMNS environmental variables lost in a script
原标题:

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)

最佳回答

You could get the lines and columns from tput:

#!/bin/bash

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

echo "Lines: " $lines
echo "Columns: " $columns
问题回答

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.

eval $( resize )

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

kill -s WINCH $$

does set the variables.

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.

Have you tried making your shebang say:

#!/bin/bash -i

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:~$ 

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

#!/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
" $COLUMNS
printf "LINES = %d
" $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.

Why not use enviroment variables on exec command like this:

docker exec -ti -e LINES=$LINES -e COLUMNS=$COLUMNS  container /bin/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 ; }




相关问题
Parse players currently in lobby

I m attempting to write a bash script to parse out the following log file and give me a list of CURRENT players in the room (so ignoring players that left, but including players that may have rejoined)...

encoding of file shell script

How can I check the file encoding in a shell script? I need to know if a file is encoded in utf-8 or iso-8859-1. Thanks

Bash usage of vi or emacs

From a programming standpoint, when you set the bash shell to use vi or emacs via set -o vi or set -o emacs What is actually going on here? I ve been reading a book where it claims the bash shell ...

Dynamically building a command in bash

I am construcing a command in bash dynamically. This works fine: COMMAND="java myclass" ${COMMAND} Now I want to dynamically construct a command that redirectes the output: LOG=">> myfile.log ...

Perform OR on two hash outputs of sha1sum

I want perform sha1sum file1 and sha1sum file2 and perform bitwise OR operation with them using bash. Output should be printable i.e 53a23bc2e24d039 ... (160 bit) How can I do this? I know echo $(( ...

Set screen-title from shellscript

Is it possible to set the Screen Title using a shell script? I thought about something like sending the key commands ctrl+A shift-A Name enter I searched for about an hour on how to emulate ...

热门标签