bash脚本:覆盖输出而不填充回滚

时间:2015-01-14 14:43:56

标签: bash shell scripting terminal

我正在研究bash脚本,每隔几秒输出一些信息。每个新输出都应该覆盖最后一个(清除终端),当我中止脚本时,当我在终端中向后滚动时,不应该看到任何输出。非常类似于'watch'(由于其他原因我不能在这里使用)。

如果我使用'clear',屏幕会被清除,但当我在终端中向后滚动时,所有输出都可见。 'reset'删除整个回滚,这也不是我想要的。使用像“printf”\ 033 [2J“'这样的ANSI序列与'clear'具有相同的效果。

任何帮助表示赞赏! 欢呼声

1 个答案:

答案 0 :(得分:3)

你可以尝试这样的事情。

#!/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

希望这会有所帮助:)