tput cols doesn't work properly in a script

白昼怎懂夜的黑 提交于 2021-02-19 07:09:55

问题


I'm using "tput cols" in a script everything goes OK except when the windows is maximized. my script is able to get any windows size correctly but when the windows is maximized, it gets a wrong value (80). Then I type "tput cols" directly into the terminal and I get the correct size (158). So my question is, how can I get the right value even when the window is maximized???

thanks in advance


回答1:


tput cols may be reading from the shell environment variable $COLUMNS instead of the TIOCGWINSZ ioctl. The shell is probably updating this variable in response to SIGWINCH, but this of course does not affect the $COLUMNS variable within your script.

Try unset COLUMNS and seeing if tput cols picks up the value from the terminal ioctl.




回答2:


First of all run:

$ shopt -s checkwinsize

Source: https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html

Try to use resize as command in order to get informations about. You will get the values you need. In order to use them in your program, you could just write something like this:

echo "Old value of COLUMNS: $COLUMNS"
# This should execute the output of resize and export the var you need
eval $(resize)
echo "New value of COLUMNS: $COLUMNS"

For more informations about resize look at man resize or check this link: http://invisible-island.net/xterm/manpage/resize.html




回答3:


For a similar issue in bash, when I was doing an

# X is a script that uses 'tput cols'
$(eval X)

... it was reverting back to 80 columns.

So, I changed my eval to:

T=`tput cols` 
$(COLUMNS=$T X)


来源:https://stackoverflow.com/questions/14308166/tput-cols-doesnt-work-properly-in-a-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!