我想每隔 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"
脚本的作用:
- 确定终端的高度(行数)
- 计算
watch
输出的可见区域 - 打印空白行以填充输出(下推输出)
- 从 stdin 中读取输出,并对其进行修剪,以便我们仅在输出超出屏幕的情况下显示输出的顶部。如果您想查看输出的底部,只需删除
cat
之后的head
命令即可。 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/