【问题标题】:How to add Progress bar for shell scripts having few commands? [closed]如何为命令很少的 shell 脚本添加进度条? [关闭]
【发布时间】:2020-11-13 06:24:27
【问题描述】:

我正在编写一个带有一些命令的 shell 脚本。我想给它添加一个进度条。

例如-

Command 1 #Progress bar at 25%
Command 2 #Progress bar at 50%
Command 3 #Progress bar at 75%
Command 4 #Progress bar at 100%    

非常感谢任何帮助。

编辑:我正在使用 linux 的 Bash 终端,并希望在终端中显示进度条。

【问题讨论】:

  • pv 可能对你有帮助。
  • 哪个操作系统/外壳? tsh、csh、bash、ksh、powershell 等?
  • 您是在寻找图形 (X) 进度条,还是基于终端的进度条?
  • @jim 我正在使用 Linux Mint 和 Bash shell
  • @dash-o 我正在寻找基于终端的进度条。

标签: bash shell scripting sh zsh


【解决方案1】:

许多解决方案最简单的方法是使用 pv 等 externat 命令

du -h /var | tail -2 | pv 

一个更好的方法是在你的脚本中使用函数来显示条形:

echo -ne '#####                     (33%)\r'
sleep 1
echo -ne '#############             (66%)\r'
sleep 1
echo -ne '#######################   (100%)\r'
echo -ne '\n'

使用滚动旋转甚至更好:

sp='/-\|'
printf ' '
while true; do
    printf '\b%.1s' "$sp"
    sp=${sp#?}${sp%???}
done

您将任务作为背景和条形启动和/或作为前景旋转 当然,您可以对信号设置条件或陷阱以在任务/命令结束时停止它。

【讨论】:

  • echo -ne 写成printf 会更安全。 POSIX 规范没有定义-n 的行为方式,任何将-e 视为要打印的内容以外的东西的shell 都完全违反了标准。 (bash 开箱即用,但它也能够在编译时或运行时通过环境变量或shopt 选项配置为符合标准,因此echo -e 不可靠即使 shell 100% 肯定是 bash)。
【解决方案2】:

试试这个:

#!/bin/bash
echo -n 'Progress: [--------------------]'
sleep 1     # <- Command 1
echo -ne '\rProgress: [#####---------------]'
sleep 1     # <- Command 2
echo -ne '\rProgress: [##########----------]'
sleep 1     # <- Command 3
echo -ne '\rProgress: [###############-----]'
sleep 1     # <- Command 4
echo -e '\rProgress: [####################]'

【讨论】:

  • 我对另一个答案的评论同样适用。 echo -necho -eecho -ne 都更安全地替换为 printf;这不仅可以提高对其他 shell 的可移植性,还可以提高您知道 shell 是 bash 但不控制活动环境变量集的上下文中的可靠性。
猜你喜欢
  • 2010-09-19
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 2015-02-15
  • 2015-11-02
  • 1970-01-01
相关资源
最近更新 更多