2011-01-13 94 views
5

我想連續檢查一個文件的內容不斷變化。 「tail -f」不足以滿足文件不增長的需求。「tail -f」替代它不滾動終端窗口

我可以用一個簡單的循環,而在bash達到同樣的效果:

while [ 1 ]; do cat /proc/acpi/battery/BAT1/state ; sleep 10; done 

它的工作原理,但它具有滾動我的終端窗口的不必要的影響。

所以,現在我想知道,有沒有一個Linux/shell命令可以顯示該文件的輸出而不需要滾動終端?

+0

你試過手錶了嗎? – Rozuur 2011-01-13 06:47:15

+0

我以前沒有收到這個建議。 – 2011-01-13 08:07:08

+0

有很多正確的答案。感謝gabuzo,SiegeX,Jander和Omnifarious。但最接近我想要的是丹尼斯威廉姆森。感謝大家花時間! – 2011-01-14 07:23:08

回答

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 

這顯然是你將不會被手型,所以你可以把它一個函數,它的文件名,秒更新之間的數,從線作爲參數的行和數量。

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 
} 

運行:

watchit /proc/acpi/battery/BAT1/state .5 0 6 

第二個參數(更新之間秒)的默認值爲1的第三個參數(起始系)默認值爲0。第四個參數(行數)默認爲整個文件。如果您省略了行數並且文件增長,則可能會導致滾動以適應新行。

編輯:我添加了一個參數來控制更新的頻率。

12
watch -n 10 cat /proc/acpi/battery/BAT1/state 

,如果你希望它強調從一個迭代到下一個差異可以添加-d標誌。

+0

+1爲`-d`標誌 – gabuzo 2011-01-13 06:50:13

+0

請注意,`watch`默認安裝在Debian中,但不是BSD。 – 2011-01-13 06:59:32

+1

@jleedev:請注意,BSD不是Linux。 – slebetman 2011-01-13 07:25:17

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 

所以,把你的例子這將是:

watch -n 10 cat /proc/acpi/battery/BAT1/state 
3

我最喜歡的,這在地方工作沒有watch,是這樣的:

while true; do clear ; cat /proc/acpi/battery/BAT1/state ; sleep 10; done 
3

的規範(正如其他人所說的,最簡單,最靈活的答案是watch。但是,如果你想看到的只是一個文件的第一行,這裏是一個替代方案,既不清零,也不滾動終端:

while line=`head -n 1 /proc/acpi/battery/BAT1/state` \ 
    && printf "%s\r" "$line" \ 
    && sleep 10 
do 
    printf "%s\r" "`echo -n "$line" | sed 's/./ /g'`" 
done 
echo 

回車是這裏的核心理念。它告訴光標返回到當前行的開始位置,如換行符,但不移動到下一行。這裏使用printf命令是因爲(1)它不會自動添加換行符,並且(2)它將\r轉換爲回車符。

第一個printf打印您的線。第二個通過用空格覆蓋它來清除它,這樣如果要打印的下一行更短,就不會看到垃圾。

請注意,如果打印的行比終端的寬度長,終端將仍然滾動。