【问题标题】:bash script: Overwrite output without filling scrollbackbash脚本:覆盖输出而不填充回滚
【发布时间】:2015-03-12 19:00:00
【问题描述】:
我正在编写每隔几秒输出一些信息的 bash 脚本。每个新输出都应该覆盖最后一个输出(清除终端),当我中止脚本时,当我在终端中向后滚动时,不应看到任何输出。与“watch”非常相似(由于其他原因我不能在这里使用)。
如果我使用“清除”,屏幕会被清除,但当我在终端中向后滚动时所有输出都是可见的。 'reset' 删除整个回滚,这也不是我想要的。使用 'printf "\033[2J"' 之类的 ANSI 序列与 'clear' 具有相同的效果。
任何帮助表示赞赏!
干杯
【问题讨论】:
标签:
bash
shell
scripting
terminal
【解决方案1】:
你可以试试这样的。
#!/bin/bash
oldrows=$(tput lines) # get the number of rows
oldcolumns=$(tput cols) # get the number of columns
count=0 #set count to 0
control_c() # Function if CTRL-C is used to exit to set
{ # stty sane again and remove the screen.
tput rmcup # Removes screen
stty sane # Allows you to type
exit #Exits script
}
Draw() # Draw function, clears screen and echos
{ # whatever you want
((x++))
tput clear
echo things to screen $x #x is there simply for this example to show screen changing
}
ChkSize() #Checks any changes to the size of screen
{ # so you can resize Screen
rows=$(tput lines)
columns=$(tput cols)
if [[ $oldcolumns != $columns || $oldrows != $rows ]];then
Draw
oldcolumns=$columns
oldrows=$rows
fi
if [[ $count -eq 10 ]]; then # Counter 10 is 1 second as loop is every 0.1
Draw # seconds. Draw and sets count to 0
count=0
fi
}
main()
{
stty -icanon time 0 min 0 # Sets read time to nothing and prevents output on screen
tput smcup # Saves current position of of cursor, and opens new screen
Draw # Draw function
count=0 #Sets count to 0
keypress='' #Sets Keypress to nothing
while [ "$keypress" != "q" ]; do #Loop will end when q is pressed,can change to whatever condition you want
rows=$(tput lines) #Sets rows and cols
columns=$(tput cols)
sleep 0.1 #To prevent it from destroying cpu
read keypress #Reads one character
(( count = count + 1)) #Increment the counter
ChkSize #Runs the checksize function
trap control_c SIGINT #Traps CTRL-C for the function.
done
stty sane #Reverts stty
tput rmcup #Removes screen and sets cursor back"
exit 0 #Exits
}
main #Runs main
希望这会有所帮助:)