【问题标题】:Scroll a shell script output without piping it into less滚动一个 shell 脚本输出而不用管道将它的输出
【发布时间】:2013-05-14 18:03:08
【问题描述】:

我有一个 bash script.sh。我可以像这样轻松滚动输出:

$ ./script.sh | less

但是如何使输出显示自动滚动,而不必通过less 传递?换句话说,我如何将该功能直接放入脚本本身?我只想像这样执行脚本:

$ ./script.sh

我知道我可以编写一个不同的脚本来执行第一个脚本并自动通过管道输出,但我不想编写另一个脚本只是为了让第一个脚本执行我希望它执行的操作.明白我的意思吗?

【问题讨论】:

    标签: bash shell scroll scripting


    【解决方案1】:

    你可以这样写你的脚本:

    #!/bin/bash
    (
    
        Your script here
    
    ) | less
    exit $PIPESTATUS 
    

    如果输出是终端,这将通过less 管道输出脚本(因此您可以在不分页的情况下使用./script.sh > file),并保留脚本的退出代码。

    【讨论】:

    • less 检测到自己重定向到文件并停止分页。 (至少在我的系统上)。你的退出代码是对的...... ;)
    • 它检查了 stdout 是否是一个终端,但正如@jm666 指出的那样,less 本身处理得很好。
    【解决方案2】:

    通常将下一个添加到您的脚本中

    #!/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
    

    【讨论】:

      【解决方案3】:

      我决定向 Bash 添加一个特殊绑定,而不是修改脚本本身。

      实际上,您将能够编写 ./script.sh 而不是 ( ./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"'
      

      因此,您将能够执行以下操作:

      1. 输入你想运行的命令。

        $ ./script.sh 
        
      2. 点击Escape退出插入模式并进入正常模式。

      3. 现在按 Shift-j 来执行该行。

      现在您应该可以从头开始滚动输出了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-17
        • 2017-01-15
        • 2018-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-27
        相关资源
        最近更新 更多