[英]Scroll a shell script output without piping it into less
我有一个bash script.sh。 我可以像这样轻松滚动输出:
$ ./script.sh | less
但是如何使输出显示自动滚动,而不必通过less
管道? 换句话说,如何将该功能直接放入脚本本身? 我只想像这样执行脚本:
$ ./script.sh
我知道我可以编写一个不同的脚本来执行第一个脚本并自动管道输出但是我不想编写另一个脚本只是为了让第一个脚本做我想做的事情。 明白我的意思了吗?
您可以像这样编写脚本:
#!/bin/bash
(
Your script here
) | less
exit $PIPESTATUS
如果输出是终端(这样你可以./script.sh > file
没有分页),这将通过less
管道脚本输出,并保留脚本的退出代码。
通常足以将下一个添加到您的脚本中
#!/bin/bash
( # add this to the start
#your old script here
date
cat /etc/passwd
df
ls -l
#end of your script
) | less #and add this to the end
或者您可以将整个脚本放入bash函数中
#!/bin/bash
the_runner() {
#your old script here
date
cat /etc/passwd
df
ls -l
#end of your script
}
the_runner "$@" | less
我没有修改脚本本身,而是决定为Bash添加一个特殊的绑定。
实际上,您将能够编写./script.sh
而不是( ./script.sh ) | more
( ./script.sh ) | more
。
这是您需要添加到.bashrc
:
# Switch to vi mode (default is emacs mode).
set -o vi
dont_scroll_down() {
# Add the command to your history.
history -s "$READLINE_LINE"
# Redirect all output to less.
bash -c "$READLINE_LINE" 2>&1 | less -eFXR
# Remove the command from the prompt.
READLINE_LINE=''
# Optionally, you can call 'set -o vi' again here to enter
# insert mode instead of normal mode after returning from 'less'.
# set -o vi
}
bind -m vi -x '"J": "dont_scroll_down"'
因此,您将能够执行以下操作:
键入要运行的命令。
$ ./script.sh
按Escape退出插入模式并进入正常模式。
现在按Shift-j执行该行。
现在您应该能够从头开始滚动输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.