"tail -f"alternate不会滚动终端窗口

Jag*_*dha 5 linux bash shell

我想连续检查一个文件,以查找不断变化的内容."tail -f"不够,因为文件的大小不会增大.

我可以在bash中使用一个简单的while循环来达到同样的效果:

while [ 1 ]; do cat /proc/acpi/battery/BAT1/state ; sleep 10; done
Run Code Online (Sandbox Code Playgroud)

虽然它有滚动我的终端窗口的不良影响,但它确实有效.

所以现在我想知道,是否有一个linux/shell命令可以在不滚动终端的情况下显示该文件的输出?

Sie*_*geX 12

watch -n 10 cat /proc/acpi/battery/BAT1/state
Run Code Online (Sandbox Code Playgroud)

-d如果您希望它突出显示从一次迭代到下一次迭代的差异,您可以添加该标志.


gab*_*uzo 9

watch是你的朋友.它使用curses,因此它不会滚动您的终端.

Usage: watch [-dhntv] [--differences[=cumulative]] [--help] [--interval=<n>] [--no-title] [--version] <command>
  -d, --differences[=cumulative]        highlight changes between updates
                (cumulative means highlighting is cumulative)
  -h, --help                            print a summary of the options
  -n, --interval=<seconds>              seconds to wait between updates
  -v, --version                         print the version number
  -t, --no-title                        turns off showing the header
Run Code Online (Sandbox Code Playgroud)

所以以你的榜样为例:

watch -n 10 cat /proc/acpi/battery/BAT1/state
Run Code Online (Sandbox Code Playgroud)


Pau*_*ce. 6

结合其他答案中的几个想法以及其他一些技巧,这将输出文件而不清除屏幕或滚动(如果提示位于屏幕底部,则第一个周期除外).

up=$(tput cuu1)$(tput el); while true; do (IFS=$'\n'; a=($(</proc/acpi/battery/BAT1/state)); echo "${a[*]}"; sleep 1; printf "%.0s$up" ${a[@]}); done
Run Code Online (Sandbox Code Playgroud)

这显然是你不能手工输入的东西,所以你可以把它作为一个函数,它将文件名,更新之间的秒数,起始行和行数作为参数.

watchit () {
    local up=$(tput cuu1)$(tput el) IFS=$'\n' lines
    local start=${3:-0} end
    while true
    do
        lines=($(<"$1"))
        end=${4:-${#lines[@]}}
        echo "${lines[*]:$start:$end}"
        sleep ${2:-1}
        # go up and clear each line
        printf "%.0s$up" "${lines[@]:$start:$end}"
    done
}
Run Code Online (Sandbox Code Playgroud)

运行:

watchit /proc/acpi/battery/BAT1/state .5 0 6
Run Code Online (Sandbox Code Playgroud)

第二个参数(更新之间的秒数)默认为1.第三个参数(起始行)默认为0.第四个参数(行数)默认为整个文件.如果省略行数并且文件增长,则可能导致滚动以容纳新行.

编辑:我添加了一个参数来控制更新的频率.