【问题标题】:How to display and refresh multiple lines in bash如何在bash中显示和刷新多行
【发布时间】:2018-12-19 14:41:09
【问题描述】:

我正在编写一个安装脚本,并希望在脚本运行过程中显示脚本的状态。

示例:

var1="pending"
var2="pending"
var3="pending"

print_status () {
echo "Status of Item 1 is: "$var1""
echo "Status of Item 2 is: "$var2""
echo "Status of Item 3 is: "$var3""
}

code that does something and then refreshes the
output above as the status of each variable changes.

【问题讨论】:

  • 试试clear。它会擦除屏幕。如需更高级的技巧,请使用 dialog 之类的内容。
  • 你能澄清一下你所说的“刷新”是什么意思吗?你的意思是你想要一些“表单”或“屏幕”的输出,只有某些字段更新?并且在给定时间可能有多个这样的字段?还是仅在 item1 完成后才开始 item2 的状态(同样在 item2 之后的 item3)?

标签: bash


【解决方案1】:

这段代码应该会给你一些想法:

while :; do
    echo "$RANDOM"
    echo "$RANDOM"
    echo "$RANDOM"
    sleep 0.2
    tput cuu1 # move cursor up by one line
    tput el # clear the line
    tput cuu1
    tput el
    tput cuu1
    tput el
done

使用man tput 了解更多信息。要查看功能列表,请使用man terminfo

【讨论】:

【解决方案2】:

我找到了现有答案中未提及的另一种解决方案。我正在为 openwrt 开发程序,tput 默认不可用。以下解决方案的灵感来自Missing tputCursor Movement

- Position the Cursor:
  \033[<L>;<C>H
     Or
  \033[<L>;<C>f
  puts the cursor at line L and column C.
- Move the cursor up N lines:
  \033[<N>A
- Move the cursor down N lines:
  \033[<N>B
- Move the cursor forward N columns:
  \033[<N>C
- Move the cursor backward N columns:
  \033[<N>D

- Clear the screen, move to (0,0):
  \033[2J
- Erase to end of line:
  \033[K

- Save cursor position:
  \033[s
- Restore cursor position:
  \033[u

至于你的问题:

var1="pending"
var2="pending"
var3="pending"

print_status () {
    # add \033[K to truncate this line
    echo "Status of Item 1 is: "$var1"\033[K"
    echo "Status of Item 2 is: "$var2"\033[K"
    echo "Status of Item 3 is: "$var3"\033[K"
}

while true; do 
    print_status
    sleep 1
    printf "\033[3A"    # Move cursor up by three line
done

【讨论】:

    【解决方案3】:

    看看这个:

    while true; do echo -ne "`date`\r"; done
    

    还有这个:

    declare arr=(
      ">...."
      ".>..."
      "..>.."
      "...>."
      "....>"
    )
    
    for i in ${arr[@]}
    do
      echo -ne "${i}\r"
      sleep 0.1
    done
    

    【讨论】:

      【解决方案4】:

      您可以使用回车来更改单个状态行上的文本。

      n=0
      while true; do
        echo -n -e "n: $n\r"
        sleep 1
        n=$((n+1))
      done
      

      如果你能把所有的计数器放在一条线上

      n=0
      m=100
      while true; do
        echo -n -e "n: $n  m: $m\r"
        sleep 1
        n=$((n+1))
        m=$((m-1))
      done
      

      这种技术似乎不能扩展到多行,尽管它确实比 tput 具有在哑终端(如 Emacs shell)上工作的优势。

      【讨论】:

        【解决方案5】:

        这并不能完全解决您的问题,但可能会有所帮助;打印每个命令执行后的状态,修改 PS1 如下:

        PS1='$PS1 $( print_status )'
        

        【讨论】:

          猜你喜欢
          • 2011-07-10
          • 2016-08-13
          • 1970-01-01
          • 2018-01-17
          • 1970-01-01
          • 2019-10-24
          • 1970-01-01
          • 1970-01-01
          • 2013-06-05
          相关资源
          最近更新 更多