bash - gnu watch : justify on the lower left of the terminal

标签 bash watch

我想每隔 N 秒对 mysql 查询应用一个 watch 命令,但希望结果显示在终端的左下角而不是左上角:

watch -n 120 "mysql_query" | column -t"

像这样显示我的结果:

--------------------------
|xxxxxxxxxxx             |
|xxxxxxxxxxx             |
|xxxxxxxxxxx             |
|                        |
|                        |
--------------------------

而我希望他们这样:

--------------------------
|                        |
|                        |
|xxxxxxxxxxx             |
|xxxxxxxxxxx             |
|xxxxxxxxxxx             |
--------------------------

建议?

最佳答案

我没有看到执行此操作的直接方法,但我设法使用以下方法强制它工作。我还没有对此进行全面测试,所以我不能保证它在所有情况下都有效。

使用这个脚本:

#!/bin/bash
TERM_HEIGHT=`tput lines`  # determine terminal height
WATCH_BANNER_HEIGHT=2  # account for the lines taken up by the header of "watch"
let VIS_LINES="TERM_HEIGHT - WATCH_BANNER_HEIGHT"  # height of visible area
(yes " " | head -n $VIS_LINES; cat | head -n $VIS_LINES) | tail -n $VIS_LINES

后处理命令的输出,因为它被 watch 调用,例如(假设脚本被保存为 align_bottom,使其可执行,并存储在您的 $PATH 中的某个位置):

watch -n 120 "mysql_query | column -t | align_bottom"

脚本的作用:

  1. 确定终端的高度(行数)
  2. 计算watch输出的可见区域
  3. 打印空白行以填充输出(下推输出)
  4. 从 stdin 中读取输出,并对其进行修剪,以便我们仅在输出超出屏幕的情况下显示输出的顶部。如果您想查看输出的底部,只需删除 cat 之后的 head 命令即可。
  5. tail 步骤 (3) 和 (4) 的输出,因此多余的填充被删除,最终输出紧贴 watch

我不得不承认这看起来有点老套,但希望它能让您更接近您想要实现的目标。


更新:

也应该可以将其作为一个函数来实现,这样它就可以轻松地放在 .bashrc 中。

function align_bottom() {
  (( VIS = $(tput lines) - 2 ))  # height of visible area
  (yes " " | head -n $VIS; cat | head -n $VIS) | tail -n $VIS
}
typeset -fx align_bottom  # !! make it callable from subshell

用法是一样的:

watch -n 120 "mysql_query | column -t | align_bottom"

请注意,watch 使用 sh -c 运行给定的命令,因此,正如 Dennis 在评论中指出的那样,在不链接 /bin 的系统上/sh/bin/bash 上面显示的函数方法将不起作用。

可以让它工作:

watch -n 120 "mysql_query | column -t | bash -c align_bottom"

但为了可移植性和可用性,简单地使用 shell 脚本方法更简洁。

关于bash - gnu watch : justify on the lower left of the terminal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8940925/

相关文章:

linux - 如何在 bash shell 中编写精美优雅的 linux 命令

git - 在shell脚本中获取git返回值

linux - 如何将字符串拆分为单个字符

ruby - Linux 服务器 sudo 命令未找到

AngularJS : watching a particular property in an array of objects for changes in the property's value

linux - 了解标志设置

visual-studio-2010 - Visual Studio 2010 : While debugging, 如何从变量中复制包含回车符的字符串值?

javascript - 使用 webpack 观看目录

windows-7 - Webpack --watch 在 Windows 上不起作用(也不是 webpack-dev-server)

BASH:我如何像 watch 命令一样输出